Sunday 27 January 2013

Playing Audio Files in Android


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" >

    <Button
        android:id="@+id/playButton"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="28dp"
        android:text="play" />

    <Button
        android:id="@+id/pauseButton"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/playButton"
        android:layout_below="@+id/playButton"
        android:layout_marginTop="34dp"
        android:text="pause" />

    <Button
        android:id="@+id/stopButton"
        android:layout_width="150dp"
        android:layout_height="wrap_content"
        android:layout_alignLeft="@+id/pauseButton"
        android:layout_centerVertical="true"
        android:text="stop" />

</RelativeLayout>

MainActivity.java:
package com.mediaplayer.ram;

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

public class MainActivity extends Activity implements OnClickListener {
Button play, pause, stop;
MediaPlayer mp;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
play = (Button) findViewById(R.id.playButton);
pause = (Button) findViewById(R.id.pauseButton);
stop = (Button) findViewById(R.id.stopButton);

mp = MediaPlayer.create(getApplicationContext(), R.raw.jenny);

play.setOnClickListener(this);
pause.setOnClickListener(this);
stop.setOnClickListener(this);

}

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.playButton:
mp.start();
break;

case R.id.pauseButton:
mp.pause();
break;

case R.id.stopButton:
mp.stop();
mp = MediaPlayer.create(getApplicationContext(), R.raw.jenny);
break;
}
}

@Override
protected void onPause() {
// TODO Auto-generated method stub
mp.pause();
super.onPause();
}

}

4 comments:

  1. what is R.raw.jenny.......can u please tell me sir

    ReplyDelete
    Replies
    1. The reference of jenny.mp3 file from raw folder under res folder...

      Delete
  2. if suppose i have 3 songs do i need to create 3 media players
    what is the procedure

    ReplyDelete
  3. i want to play 2 songs. how can i write the code. thanks

    ReplyDelete