- Java code
import android.app.Activity;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.view.SurfaceHolder;import android.view.SurfaceView;public class MediaPlayDemo extends Activity { private SurfaceView surfaceView = null ; private SurfaceHolder surfaceHolder = null ; private MediaPlayer mp = null ; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); surfaceView = new SurfaceView(this); this.surfaceHolder = this.surfaceView.getHolder(); this.surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); this.setContentView(this.surfaceView); this.mp = new MediaPlayer(); try { mp.setDataSource("/sdcard/wozhinvrenxin.mp4"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } this.mp.setDisplay(surfaceHolder); this.mp.setAudioStreamType(AudioManager.STREAM_MUSIC); try { this.mp.prepare(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } this.mp.start(); }}
------解决方案--------------------
原因是:MediaPlayer开始播放后,SurfaceView还没有创建出来,因此会出现有声音没图像,解决办法:
通过surfaceHolder.addCallback监听surfaceCreate事件后再播放;
public class MediaPlayDemo extends Activity implements SurfaceHolder.Callback
{
private SurfaceView surfaceView = null ;
private SurfaceHolder surfaceHolder = null ;
private MediaPlayer mp = null ;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
surfaceView = new SurfaceView(this);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
surfaceHolder.addCallback(this);
setContentView(surfaceView);
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
// TODO Auto-generated method stub
mp = new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDisplay(surfaceHolder);
try {
mp.setDataSource("/sdcard/DownAndPlay/xyj.mp4");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepare();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
}
------解决方案--------------------
SurfaceView没有创建成功,所以没有视频