SurfaceView, MediaPlayer and Prepare Failed

I was trying to get a video to play on a SurfaceView, but I kept getting an exception:

IOException: Prepare failed.: status=0x1

After looking around, I still was not able to find out how to get the video to play. It was working fine in a VideoView, but as soon as I tried the MediaPlayer, it threw. When I called the Prepare method, it threw, but if I called PrepareAsync, it just failed with an error to the log.

I eventually found the problem, it was just a single line. I am not sure if this is a bug, or there is some other reason:

mediaPlayer.SetDataSource(path);

If I specify the path to the video using a Uri, all works fine:

mediaPlayer.SetDataSource(this, Uri.Parse(path));

So that was annoying, but it’s all over now.

Playing a video on a SurfaceView using a MediaPlayer is very useful if you want to create your own custom media playback controls. The VideoView with the MediaController is great, but there is no way to easily customize the actual controls.

Here is the snippet of code that can be used to play video. It is assumed that the surface has been created already and available in the holder variable:

var path = string.Format(
    "android.resource://{0}/{1}", 
    PackageName, Resource.Raw.video);

// create the player
var mediaPlayer = new MediaPlayer();
mediaPlayer.SetDataSource(this, Uri.Parse(path));
mediaPlayer.SetAudioStreamType(Stream.Music);
mediaPlayer.SetDisplay(holder);

// prepare the player and the surface
bool isPrepared = false;
bool isSizeSet = false;
mediaPlayer.Prepared += (sender, e) => {
    isPrepared = true;
    if (isPrepared && isSizeSet) {
        mediaPlayer.Start();
    }
};
mediaPlayer.VideoSizeChanged += (sender, e) => {
    holder.SetFixedSize(e.Width, e.Height);
    isSizeSet = true;
    if (isPrepared && isSizeSet) {
        mediaPlayer.Start();
    }
};

// start the process
mediaPlayer.PrepareAsync();

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s