4

我有一个带有以下代码的 MediaPlayerActivity: 此代码基本上尝试从 http url 获取视频流并加载它,但由于某种原因它不断崩溃。

public class MediaPlayerActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.video_player);
        SurfaceView v = (SurfaceView) findViewById(R.id.surface_video); 
        SurfaceHolder holder = v.getHolder(); 
        holder.setFixedSize(400,300); 

        MediaPlayer mp = MediaPlayer.create(this, Uri.parse("http://stream-url.com/playlist.m3u8")); 
        mp.setDisplay(holder);
        //mp.setAudioStreamType(2); 
        try {
            //mp.prepare();
            mp.start();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }

}

视频播放器.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_video" 
android:layout_width="250px" 
android:layout_height="250px"> 
</SurfaceView> 
<LinearLayout 
android:orientation="horizontal" 
android:layout_height="wrap_content" 
android:layout_width="fill_parent" 
android:padding="10dip" 
> 
</LinearLayout> 
</LinearLayout> 

当我使用以下代码进行此活动时,它会崩溃:

Intent myIntent = new Intent(HomeActivity.this, MediaPlayerActivity.class);
                    HomeActivity.this.startActivity(myIntent);

我究竟做错了什么?

4

1 回答 1

4

没有日志,有两个建议:

  1. 尝试实施SurfaceHolder.Callback.surfaceCreated().
  2. 尝试使用MediaPlayer.create()接受SurfaceHolder

(1) 详情

当您调用start(). 您应该使用SurfaceHolder.Callback.surfaceCreated()` MediaPlayer.setDisplay()MediaPlayer.start() only after surface is created. To do this, you should add override例如,您的代码可能如下所示。

public class MediaPlayerActivity extends Activity implements SurfaceHolder.Callback {
    MediaPlayer mp; 

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        this.setContentView(R.layout.video_player);
        SurfaceView v = (SurfaceView) findViewById(R.id.surface_video); 
        SurfaceHolder holder = v.getHolder(); 
        holder.setFixedSize(400,300);
        holder.addCallback(this). 

        mp = MediaPlayer.create(this, Uri.parse("http://stream-url.com/playlist.m3u8")); 

    @Override
    public void surfaceCreated(SurfaceHolder holder) {

        mp.setDisplay(holder); 
        try {
            mp.start();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
}

(2) 详情

似乎还有其他MediaPlayer.create()接受SurfaceHolder作为参数之一 - 你可以尝试一下:http://developer.android.com/reference/android/media/MediaPlayer.html#create(android.content.Context, android.net.Uri, android.view.SurfaceHolder)

于 2012-07-10T10:22:15.027 回答