Issue when trying to play media file using android.media.MediaPlayer and SurfaceView?
I am trying to play a .mp4 file using the android.media.MediaPlayer class.I am trying it out on the emulator.Unfortunately all i see is a blank screen when running the application.
I have placed the file testmp4 in the folder mnt/sdcard/
Here is the code that i am using.Can someone tell me what i am doing wrong?
package com.mediaplayer;
import java.io.IOException;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
public class MyPlayBack extends Activity implements SurfaceHolder.Callback{
/** Called when the activity is first created. */
private MediaPlayer mediaPlayer;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mediaPlayer=new MediaPlayer();
SurfaceView surface=(SurfaceView)findViewById(R.id.surface);
SurfaceHolder holder=surface.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
holder.setFixedSize(400, 300);
}
@Override
public void surfaceChanged(SurfaceHolder 开发者_如何学JAVAholder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer.setDisplay(holder);
try {
mediaPlayer.setDataSource("/sdcard/testmp4.mp4");
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
mediaPlayer.release();
}
}
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<SurfaceView
android:id="@+id/surface"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
/>
</LinearLayout>
Edit:Lately i found that when I keep the application running for a long time.I see the blank white screen.But when i press the back button I can see that the frame of the video clip for a sec before the application closes.I think that the video is playing behind the white screen.How to bring it upfront.
Why re-invent the wheel? Use VideoView, it is meant for that. If you want to see how to see it right, look at the VideoView source.
Also, emulators are no-good for using video. Use a real device for video application development / testing.
精彩评论