8
8
9
9
public class AudioFileReader {
10
10
private static final String AUDIO_FILE = "output.raw" ;
11
- public static final Integer SAMPLE_RATE = 44100 ;
12
- public static final Integer SAMPLE_NUM_OF_CHANNEL = 2 ;
13
- public static final Integer BITS_PER_SAMPLE = 16 ;
14
- private static final Integer SAMPLES = 441 ;
15
- private static final Integer BUFFER_SIZE = SAMPLES * BITS_PER_SAMPLE / 8 * SAMPLE_NUM_OF_CHANNEL ;
16
- private static final Integer PUSH_INTERVAL = SAMPLES * 1000 / SAMPLE_RATE ;
11
+ public static final int SAMPLE_RATE = 44100 ;
12
+ public static final int SAMPLE_NUM_OF_CHANNEL = 2 ;
13
+ public static final int BITS_PER_SAMPLE = 16 ;
14
+
15
+ public static final float BYTE_PER_SAMPLE = 1.0f * BITS_PER_SAMPLE / 8 * SAMPLE_NUM_OF_CHANNEL ;
16
+ public static final float DURATION_PER_SAMPLE = 1000.0f / SAMPLE_RATE ; // ms
17
+ public static final float SAMPLE_COUNT_PER_MS = SAMPLE_RATE * 1.0f / 1000 ; // ms
18
+
19
+ private static final int BUFFER_SAMPLE_COUNT = (int ) (SAMPLE_COUNT_PER_MS * 10 ); // 10ms sample count
20
+ private static final int BUFFER_BYTE_SIZE = (int ) (BUFFER_SAMPLE_COUNT * BYTE_PER_SAMPLE ); // byte
21
+ private static final long BUFFER_DURATION = (long ) (BUFFER_SAMPLE_COUNT * DURATION_PER_SAMPLE ); // ms
17
22
18
23
private final Context context ;
19
24
private final OnAudioReadListener audioReadListener ;
@@ -62,16 +67,21 @@ public void run() {
62
67
}
63
68
Process .setThreadPriority (Process .THREAD_PRIORITY_URGENT_AUDIO );
64
69
pushing = true ;
70
+
71
+ long start_time = System .currentTimeMillis ();;
72
+ int sent_audio_frames = 0 ;
65
73
while (pushing ) {
66
- long before = System .currentTimeMillis ();
67
74
if (audioReadListener != null ){
68
75
audioReadListener .onAudioRead (readBuffer (), System .currentTimeMillis ());
69
76
}
77
+ ++ sent_audio_frames ;
78
+ long next_frame_start_time = sent_audio_frames * BUFFER_DURATION + start_time ;
70
79
long now = System .currentTimeMillis ();
71
- long consuming = now - before ;
72
- if (consuming < PUSH_INTERVAL ){
80
+
81
+ if (next_frame_start_time > now ){
82
+ long sleep_duration = next_frame_start_time - now ;
73
83
try {
74
- Thread .sleep (PUSH_INTERVAL - consuming );
84
+ Thread .sleep (sleep_duration );
75
85
} catch (InterruptedException e ) {
76
86
e .printStackTrace ();
77
87
}
@@ -90,7 +100,7 @@ public void run() {
90
100
}
91
101
92
102
private byte [] readBuffer () {
93
- int byteSize = BUFFER_SIZE ;
103
+ int byteSize = BUFFER_BYTE_SIZE ;
94
104
byte [] buffer = new byte [byteSize ];
95
105
try {
96
106
if (inputStream .read (buffer ) < 0 ) {
0 commit comments