Using AudioTrack in AudioTrack.MODE_STATIC?

4.6k Views Asked by At

I've found lots of tutorials and posts showing how to use AudioTrack to play wav files in AudioTrack.MODE_STREAM and I've successfully implemented this example.

However I'm having issues with performance when playing multiple audio tracks at once and thinking that I should first create the tracks using AudioTrack.MODE_STATIC then just call play each time.

I can't find any resources on how to implement this. How can I do this?

Thanks

1

There are 1 best solutions below

5
On

The two main sticking points for me were realizing that .write() comes first and that the instantiated player must have the size of the entire clip as the buffer_size_in_bytes. Assuming you have recorded a PCM file using AudioRecord, you can play it back with STATIC_MODE like so...

File file = new File(FILENAME);
int audioLength = (int)file.length();
byte filedata[] = new byte[audioLength];
try{
    InputStream inputStream = new BufferedInputStream(new FileInputStream(FILENAME));
    int lengthOfAudioClip = inputStream.read(filedata, 0, audioLength);
    player = new AudioTrack(STREAM_TYPE, SAMPLE_RATE, CHANNEL_OUT_CONFIG, AUDIO_FORMAT,audioLength, AUDIO_MODE);
    player.write(filedata, OFFSET, lengthOfAudioClip);
    player.setPlaybackRate(playbackRate);
    player.play();
 }