Android playing audio

  • by

Android playing audio

In your android application create a new folder in your res folder named raw.

Download following sound file from the link below. It’s not necessary, you can use yours too.
Copy the downloaded audio file in the raw folder with name ding_dong.mp3.

Download Audio File

And Image file from IconFinder.com and copy this icon image in your res>drawable-hdpi folder.

Now edit the activity_main.xml file as below :

activity_main.xml :

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#1c1c1c" >

<TextView
android:id="@+id/txtheader"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_marginTop="15dp"
android:gravity="center_horizontal"
android:padding="10dp"
android:text="Playing Sound in Android"
android:textColor="#fff"
android:textSize="20sp" />

<ImageView
android:id="@+id/imgView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:contentDescription="Audio Image"
android:src="@drawable/audio" />

</RelativeLayout>

This will create following layout :

android playing audio

Now edit the MainActivity.java class file with :

MainActivity.java :

package com.example.audioPlayback;

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

public class MainActivity extends Activity {
MediaPlayer md;
ImageView img;

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

md = MediaPlayer.create(MainActivity.this, R.raw.ding_dong); // declaration of media file
img = (ImageView) findViewById(R.id.imgView);

img.setOnClickListener(new View.OnClickListener() {

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
md.start(); // code for playing the audio.
}
});

}
}

That’s all. You can test the code.

Please comment below if you need any help.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.