MediaPlayer




A MediaPlayer is an object that plays music and video.

Example:

import android.content.*;
import android.media.*;


MediaPlayer mp;



mp = MediaPlayer.create(thisContext, R.raw.explosion);
// thisContext is the context passed to the onCreate method
// explosion.mp3 should be placed in the res/raw folder


Methods:

isPlaying() // to determine if it is playing (returns a boolean)
start() // to start the playing
stop() // to stop the playing
release() // to release the resources
setLooping() // to play it over and over


A starter from the website article is shown below:
How to Play Media Article



Playing Audio

MediaPlayer is the easier way, if you just want to play an audio file in the background, somewhere in an appliaction. There are no ui controls here, but of course you can use MediaPlayer.stop(), play(), seekTo() ,etc. Just bind the needed functions to a button, gesture, or event. As you can see, it also throws a lot of exceptions, which you need to catch.

public void audioPlayer(String path, String fileName){
    //set up MediaPlayer    
    MediaPlayer mp = new MediaPlayer();

    try {
        mp.setDataSource(path+"/"+fileName);
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        mp.prepare();
    } catch (IllegalStateException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    mp.start();
}

Playing Video

In this example, I open a video file, and decide if I want it to autoplay after it is loaded.
You propably want to store your video files, on the sd card. You can get the path to the sd card via: Environment.getExternalStorageDirectory().

public void videoPlayer(String path, String fileName, boolean autoplay){
    //get current window information, 
//and set format, set it up differently,
//if you need some special effects
    getWindow().setFormat(PixelFormat.TRANSLUCENT);

    //the VideoView will hold the video
    VideoView videoHolder = new VideoView(this);
 
//MediaController is the ui control howering above the video (just like in the default youtube player).
    videoHolder.setMediaController(new MediaController(this));
 
//assing a video file to the video holder
    videoHolder.setVideoURI(Uri.parse(path+"/"+fileName));
 
//get focus, before playing the video.
    videoHolder.requestFocus();

    if(autoplay){
        videoHolder.start();
    }
}