12
12
import javax .sound .sampled .LineUnavailableException ;
13
13
import javax .sound .sampled .TargetDataLine ;
14
14
import java .io .ByteArrayOutputStream ;
15
+ import java .util .Arrays ;
15
16
16
17
/**
17
18
* Application that shows real-time spectrum
18
19
*/
19
20
public class ShowRealTimeSpectrumApp {
20
21
22
+ private final static int BUCKETS_AMOUNT = 1_000 ;
23
+
21
24
public static void main (String [] args ) throws LineUnavailableException {
22
25
FrequencyScanner frequencyScanner = new FrequencyScanner ();
23
- AudioFormat audioFormat = getAudioFormat ();
26
+ AudioFormat audioFormat = buildAudioFormat ();
24
27
DataLine .Info dataLineInfo = new DataLine .Info (TargetDataLine .class , audioFormat );
25
28
26
29
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream ();
@@ -31,6 +34,8 @@ public static void main(String[] args) throws LineUnavailableException {
31
34
chartContainer .show ();
32
35
33
36
byte tempBuffer [] = new byte [10_000 ];
37
+ double [] xData = new double [BUCKETS_AMOUNT ];
38
+ double [] yData = new double [BUCKETS_AMOUNT ];
34
39
while (true ) {
35
40
targetDataLine .start ();
36
41
int count = targetDataLine .read (tempBuffer , 0 , tempBuffer .length );
@@ -45,24 +50,25 @@ public static void main(String[] args) throws LineUnavailableException {
45
50
double [] frequencies = frequencyInfoContainer .frequencies ();
46
51
double [] magnitudes = frequencyInfoContainer .magnitudes ();
47
52
48
- int N = 1_000 ;
49
- double [] xData = new double [ N ] ;
50
- double [] yData = new double [ N ] ;
51
- for (int bucketIndex = 0 ; bucketIndex < N ; bucketIndex ++) {
52
- xData [bucketIndex ] = frequencies [(int ) ((bucketIndex + 0.5 ) * magnitudes . length / N )];
53
+ Arrays . fill ( xData , 0 ) ;
54
+ Arrays . fill ( yData , 0 ) ;
55
+ final int magnitudesPerBucket = magnitudes . length / BUCKETS_AMOUNT ;
56
+ for (int bucket = 0 ; bucket < BUCKETS_AMOUNT ; bucket ++) {
57
+ xData [bucket ] = frequencies [(int ) ((bucket + 0.5 ) * magnitudesPerBucket )];
53
58
54
- for (int i = 0 ; i < magnitudes . length / N ; i ++) {
55
- yData [bucketIndex ] += magnitudes [bucketIndex * magnitudes . length / N + i ];
59
+ for (int i = 0 ; i < magnitudesPerBucket ; i ++) {
60
+ yData [bucket ] += magnitudes [bucket * magnitudesPerBucket + i ];
56
61
}
57
62
}
58
- var maxFrequency = frequencyInfoContainer .maxFrequency ();
59
63
64
+ var maxFrequency = frequencyInfoContainer .maxFrequency ();
60
65
String title = String .format ("%1$.0f Hz" , maxFrequency );
66
+
61
67
chartContainer .update (xData , yData , title );
62
68
}
63
69
}
64
70
65
- private static AudioFormat getAudioFormat () {
71
+ private static AudioFormat buildAudioFormat () {
66
72
return new AudioFormat (44_100.0F , 16 , 1 , true , false );
67
73
}
68
74
0 commit comments