Audio Track keep playing sound after audio track released

691 views Asked by At

I am using an Audio Track to play a sound.I am initializing the Audio Track in this way.

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);

Then i am generating the sound in this way.

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);
}

Now i am playing the sound like :

audioTrack.write(generatedSnd, 0, generatedSnd.length);
audioTrack.play();

And stopping the track like the way:

audioTrack.release();
audioTrack.flush();
System.out.println("!!running"+audioTrack.getPlayState());
audioTrack = null;

Now problem is that if I do the process(play and stop) continuously some time audio is playing after the track has released.I have checked the play state which is showing 1 at the time of release but audio is still playing.

Thanks In Advance.

1

There are 1 answers

0
Shawn Lu On

Following code works to me.

audioTrack.stop();
audioTrack.flush();
audioTrack.release();
audioTrack = null;