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();
}

}