main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
>
<Button
android:id="@+id/Button1"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="Start"
android:gravity="left|center"
android:onClick="playMusic"/>
<Button
android:id="@+id/Button2"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:text="Stop"
android:gravity="left|center"
android:onClick="stopMusic"/>
</LinearLayout>
MediaBasic.java
package com.peshal.mediaplayerbasics;
import java.io.IOException;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
public class MediaBasic extends Activity {
MediaPlayer ourmediaPlayer = new MediaPlayer();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void playMusic(View view) {
String url="http://archive.org/download/testmp3testfile/mpthreetest.mp3";
ourmediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
ourmediaPlayer.setDataSource(url);
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
ourmediaPlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
ourmediaPlayer.start();
}
public void stopMusic(View view) {
ourmediaPlayer.stop();
ourmediaPlayer.release();
this.finish();
}
}