I am trying to use AudioTrack to play back sample data. I hear no sound from the device but I see this in the logcat:
AudioTrack: Use of stream types is deprecated for operations other than volume control
AudioTrack: See the documentation of AudioTrack() for what to use instead with android.media.AudioAttributes to qualify your playback use case
I have tried many examples that I have found online and they all seem to have the same problem. The examples are typically more than 4 years old so the problem must relate to changes in recent Android APIs.
I am currently trying to get this code to work: github example
It's playSound() method looks like this:
protected void playSound(int sampleRate, byte[] soundData) {
try {
int bufferSize = AudioTrack.getMinBufferSize(sampleRate, AudioFormat.CHANNEL_OUT_MONO, AudioFormat.ENCODING_PCM_16BIT);
//if buffer-size changing or no previous obj then allocate:
if (bufferSize != audTrackBufferSize || audioTrack == null) {
if (audioTrack != null) {
//release previous object
audioTrack.pause();
audioTrack.flush();
audioTrack.release();
}
//allocate new object:
audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC,
sampleRate, AudioFormat.CHANNEL_OUT_MONO,
AudioFormat.ENCODING_PCM_16BIT, bufferSize,
AudioTrack.MODE_STREAM);
audTrackBufferSize = bufferSize;
}
float gain = (float) (volume / 100.0);
//noinspection deprecation
audioTrack.setStereoVolume(gain, gain);
audioTrack.play();
audioTrack.write(soundData, 0, soundData.length);
} catch (Exception e) {
Log.e("tone player", e.toString(), e);
}
I have had a look at the Android developer documentation here but I cannot work out what needs to be changed. Is it complaining about use of AudioManager.STREAM_MUSIC, AudioManager.MODE_STREAM or both? What should it be changed to?
There are no examples of how to playback sample data in the Android developer documentation.
Using the new constructor for the AudioTrack worked for me. You can do it like that: