Play audio (mp3, ogg) from an SD card using AudioTrack

I want to play an audio file from an SD card using AudioTrack. I tried with this code:

int minBufferSize = AudioTrack.getMinBufferSize(8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT); int bufferSize = 512; AudioTrack at = new AudioTrack(AudioManager.STREAM_MUSIC, 8000, AudioFormat.CHANNEL_CONFIGURATION_MONO, AudioFormat.ENCODING_PCM_16BIT, minBufferSize, AudioTrack.MODE_STREAM); int i = 0; byte[] s = new byte[bufferSize]; FileInputStream fin = new FileInputStream(path); DataInputStream dis = new DataInputStream(fin); at.play(); while ((i = dis.read(s, 0, bufferSize)) > -1) { at.write(s, 0, i); } at.stop(); at.release(); dis.close(); fin.close(); 

But it does not play the audio file properly. Instead of the original sound, it reproduces some kind of noisy sound.

+4
source share
2 answers

From the following link, I found that AudioTrack only plays PCM audio, http://developer.android.com/guide/topics/media/index.html

And look at this code. http://mindtherobot.com/blog/624/android-audio-play-an-mp3-file-on-an-audiotrack/ you are provided with information on how to play the MP3 file on AudioTrack.

Hope this helps you.

+6
source

The AudioTrack class only supports PCM audio, so you hear noise.

Use MediaPlayer or SoundPool if you want to play compressed audio files such as .mp3 and .ogg.
Alternatively, you can decode compressed audio in your application and write the received PCM data to AudioTrack, but this is a much more complicated task.

+3
source

All Articles