我正在使用音轨播放声音。我正在以这种方式初始化音轨。
numSamples = duration * sampleRate;
sample = new double[numSamples];
generatedSnd = new byte[2 * numSamples];
length_snd = generatedSnd.length;
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate,
AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT,
length_snd, AudioTrack.MODE_STATIC);
然后我以这种方式产生声音。
for (int i = 0; i < numSamples; ++i) {
freqOfTone = freqOfTone + 1;
sample[i] = Math.sin(2 * Math.PI * i / (sampleRate / freqOfTone));
if(freqOfTone > 22500){
freqOfTone = 10000;
}
}
int idx = 0;
for (final double dVal : sample) {
// scale to maximum amplitude
final short val = (short) ((dVal * 32767));
// in 16 bit wav PCM, first byte is the low order byte
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
现在我正在播放声音:
audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();
按照这样的方式停止赛道:
audioTrack.release();
audioTrack.flush();
System.out.println("!!running"+audioTrack.getPlayState());
audioTrack = null;
现在的问题是,如果我在音轨播放后连续播放(播放和停止)一段时间音频正在播放。我已经检查了播放状态,该状态在发布时显示为1,但音频仍在播放。
提前致谢。
答案 0 :(得分:0)
以下代码对我有用。
audioTrack.stop();
audioTrack.flush();
audioTrack.release();
audioTrack = null;