Friday, October 26, 2012

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

import android.content.Context;
import android.content.res.AssetFileDescriptor;

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

    public AudioPlayer(String name, Context context) {
        fileName = name;
        contex = context;

    //Play Audio
    public void playAudio() {
        mp = new MediaPlayer();
        try {
            AssetFileDescriptor descriptor = contex.getAssets()
                    descriptor.getStartOffset(), descriptor.getLength());
            mp.setVolume(3, 3);

        } catch (IllegalArgumentException e) {
        } catch (IllegalStateException e) {
        } catch (IOException e) {
    //Stop Audio
    public void stop() {

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


francois xiong 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.

Irudaya Raj said...
This comment has been removed by the author.
Irudaya Raj said...

Hello Francois,

Code snippet to input file name in each coding.

String ringtoneFileName = "Ringtone1.mp3";

AudioPlayer audioPlayer = new AudioPlayer(ringtoneFileName,context);