9

我想做的是在开始播放视频之前在 SurfaceView 上显示背景图像。

  1. 我试图只绘制一个 jpeg 图像作为 SurfaceView 的背景。有效。
  2. 我还尝试在 SurfaceView 上播放视频。它也奏效了。

但是,当我尝试在 surfaceCreated 函数中将 jpeg 图像绘制为 Surface 的背景然后播放视频时。我收到错误“[SurfaceView] 连接:已连接”。

有任何想法吗?谢谢。

这是部分代码

@Override
public void surfaceCreated(SurfaceHolder holder) {
    try {
    Bitmap background = BitmapFactory.decodeResource(getResources(), R.drawable.pic1);
    float scale = (float) background.getHeight()/(float)mPreview.getHeight();
    int newWidth = Math.round(background.getWidth()/scale);
    int newHeight = Math.round(background.getHeight()/scale);
    mScaledBitmap = Bitmap.createScaledBitmap(background, newWidth, newHeight, true);
    Canvas canvas = mHolder.lockCanvas();
    canvas.drawBitmap(mScaledBitmap, 0, 0, null);
    mHolder.unlockCanvasAndPost(canvas);
    } catch (Exception e)
    {}
            // initialize mediaplayer
    try {
        mMediaPlayer = new MediaPlayer();
        mMediaPlayer.setDataSource("/sdcard/Movies/2.mp4");
        mMediaPlayer.setDisplay(mHolder);
        mMediaPlayer.setLooping(true);
        mMediaPlayer.prepare();
        mMediaPlayer.setOnPreparedListener(this);
        mMediaPlayer.setOnCompletionListener(this);
    } catch (IOException e) {
        e.printStackTrace();
        Log.e(TAG, "error: " + e.getMessage(), e);
    } catch (Exception e) {
        e.printStackTrace();
        Log.e(TAG, "error: " + e.getMessage(), e);  
    }
}

@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
        int height) {
    // TODO Auto-generated method stub
    Log.i(TAG, "surfaceChanged(w="+ width + ", h=" + height);
    mSurfaceWidth = width;
    mSurfaceHeight = height;
    mVideoWidth = mMediaPlayer.getVideoWidth();
    mVideoHeight = mMediaPlayer.getVideoHeight();
    Log.i(TAG, "video size w=" + mVideoWidth + ", h=" + mVideoHeight +")");     
}


@Override
public void onPrepared(MediaPlayer mp) {
    // TODO Auto-generated method stub
    Log.i(TAG, "onPrepared");
    mMediaPlayer.start();
}
4

2 回答 2

0

我认为问题是您可以使用外部 SurfaceHolder 只需将 mHolder 对象更改为本地持有者对象即可。我不能在我这边尝试。

于 2013-12-30T10:01:06.467 回答
0

Here are couple of things that I see wrong based on my experience with MediaPlayer.

  • First, use prepareAysnc() instead of prepare().
  • Second, set the listeners first before calling prepare(). In your case, mMediaPlayer.setOnPreparedListener(this)

is followed by prepare(). Consider scenario where prepare() upon completion looks for OnPreparedListener and does not finds it, because you haven't set it yet. And setting it afterwards is not going to help since, media player is already in PREPARED state and thus you'd never get onPrepared() callback.

Thus in your case, mMediaPlayer.start() may never get executed.

In general, set all the necessary listeners first, before invoking their triggers.

于 2015-08-03T19:14:04.903 回答