Translate

Sunday, December 30, 2012

Android App Development 101 3rd tutorial; MediaPlayer Basics

In this tutorial, I will be be making a basic android media player which streams a mp3 file from a url. Just like previous tutorial, this app has two buttons, one to play the music and the second to stop the music, release the media player object and exit the app. Here is the code:

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

}

}


No comments:

Post a Comment