Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play Audio (mp3, ogg) from sd card with AudioTrack

I want to play audio file from SD card with AudioTrack. I've 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 doesn't play audio file properly. Instead of original audio it plays some kind noise sound.

like image 249
asish Avatar asked Mar 04 '13 11:03

asish


2 Answers

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

And Please have a look on this code. http://mindtherobot.com/blog/624/android-audio-play-an-mp3-file-on-an-audiotrack/ this is provided the information about how to Play an MP3 file on an AudioTrack.

Hope this helps u .

like image 166
itsrajesh4uguys Avatar answered Oct 23 '22 23:10

itsrajesh4uguys


The AudioTrack class only supports PCM audio data, that's why you're hearing noise.

Use MediaPlayer or SoundPool if you want to play compressed audio files like .mp3 and .ogg.
Alternatively you could decode the compressed audio in your app and write the resulting PCM data to an AudioTrack, but that's a much bigger task.

like image 35
Michael Avatar answered Oct 24 '22 00:10

Michael