Friday, October 26, 2012

Play audio file (.mp3) from asset folder in android.

import java.io.IOException;
import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;

public class AudioPlayer {
  
    String fileName;
    Context contex;
    MediaPlayer mp;

    //Constructor
    public AudioPlayer(String name, Context context) {
        fileName = name;
        contex = context;
        playAudio();
    }

    //Play Audio
    public void playAudio() {
        mp = new MediaPlayer();
        try {
            AssetFileDescriptor descriptor = contex.getAssets()
                    .openFd(fileName);
            mp.setDataSource(descriptor.getFileDescriptor(),
                    descriptor.getStartOffset(), descriptor.getLength());
            descriptor.close();
            mp.prepare();
            mp.setLooping(true);
            mp.start();
            mp.setVolume(3, 3);

        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //Stop Audio
    public void stop() {
        mp.stop();
    }
}


Call this class from any activity like as new AudioPlayer(file_name, mContext);

3 comments:

Unknown said...

I'd like to know how else to input the file names into each coding. Maybe a underline used too show where to input the files names.

Unknown said...
This comment has been removed by the author.
Unknown said...

Hello Francois,

Code snippet to input file name in each coding.

String ringtoneFileName = "Ringtone1.mp3";

AudioPlayer audioPlayer = new AudioPlayer(ringtoneFileName,context);

audioPlayer.playAudio();