Wednesday, November 18, 2015

Play Audio From Asset Directory in Android



Description:

Many applications need small audio file integrated in app only. For Example, Simple 2D bomb blast game, it requires bomb blast sound effect. It is necessary for developer to add sound effect in this type of app.Another reason is make application more attractive. Sound effect shapes your app more attractive and look different than other apps. Here is the code which help you to play audio file from asset file.

We have created this app with very easy way, you can use the same file for different application with copy/paste file.

First, Create AudioPlayer.java file:

AudioPlayer.java


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() {
    if(mp != null){
       mp.stop();
    }
   }
   
   //Pause Audio
   public void pause(){
    if(mp != null){
    mp.pause();
    }
   }
   
}

Now, Add 3 Buttons Play,Pause and Stop in activity_main.xml file.

activity_main.xml


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:orientation="vertical" >

        <Button
            android:id="@+id/buttonPlay"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Play"
            android:drawableLeft="@android:drawable/ic_media_play" />

        <Button
            android:id="@+id/buttonPause"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Pause"
            android:drawableLeft="@android:drawable/ic_media_pause" />

        <Button
            android:id="@+id/buttonStop"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Stop"
            android:drawableLeft="@drawable/stop" />

    </LinearLayout>

</RelativeLayout>


Copy below code in MainActivity.java file

MainActivity.java


import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btnPlay, btnPause, btnStop;
AudioPlayer audioPlayer;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

btnPlay = (Button) findViewById(R.id.buttonPlay);
btnPause = (Button) findViewById(R.id.buttonPause);
btnStop = (Button) findViewById(R.id.buttonStop);

context = getApplicationContext();
audioPlayer = new AudioPlayer("audio_sample.mp3", context);

btnPlay.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
audioPlayer.playAudio();
btnPlay.setEnabled(false);
}
});

btnPause.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnPlay.setEnabled(true);
if (audioPlayer != null) {
audioPlayer.pause();
}
}
});

btnStop.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
btnPlay.setEnabled(true);
if (audioPlayer != null) {
audioPlayer.stop();
}
}
});
}
}


Download Full Source Code: GitHub



5 comments: