Android development primer: Working with Audio in Android

We can have audios in our Android application. It can be used as and when required and is decided by the Application Developer.
Adding and configuring audios to our application is fairly simple.

In this post I am going to show you how to add audios to your Android Application and play the audio. Complete Source Code is at the bottom.

  • Navigate to <yourprojectname> -> res.
  • Now right click on the res folder and select New -> Folder.
  • Name this folder raw. All the audios that you have in your application, necessarily need to be in a folder names raw inside the res folder.
  • Now copy-paste an audio file inside the raw folder. You can do this by navigating to the Eclipse workspace on your system and then to your project’s res folder, or you can drag and drop it in Eclipse itself.
  • Once the audio file is in your raw folder, create an Activity and set the content view. Make sure you have a button in the activity, so that the audio can be played when the button is clicked.
  • Now in the onClick() method of the button write the following code.
    [java]
    MediaPlayer mp = MediaPlayer.create(Main.this, R.raw.beep);
    mp.start();
    [/java]
  • Worth noting here, is the MediaPlayer class and that we have not used a constructor but a static method to initialize it. MediaPlayer class is used for any media related operations that you might have to perform. The mp.start() method starts the MediaPlayer. 
  • Save your work and execute it on an emulator/device.
  • It might happen that the audio file does not play on the emulator. In such circumstances, you must install the application on a device and check whether it works

COMPLETE SOURCE CODE

[java]
package com.nero.myfirstapp;

import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class Main extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button but = (Button) findViewById(R.id.but);

but.setOnClickListener(new OnClickListener() {

@Override
public void onClick(View arg0) {
MediaPlayer mp = MediaPlayer.create(MainActivity.this, R.raw.beep);
mp.start();
}

});

}
}

[/java]

Leave a Comment

Your email address will not be published. Required fields are marked *