Android:如何创建视频播放器?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1188346/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 02:46:04  来源:igfitidea点击:

Android: How to create video player?

androidmedia-player

提问by Niko Gamulin

I am creating a video recorder and would like to create video player to preview the recorded videos. Modifying the code from this pageI have created a MediaPreview class the following way:

我正在创建一个录像机,并想创建视频播放器来预览录制的视频。修改此页面中的代码我通过以下方式创建了一个 MediaPreview 类:

public class MediaPreview extends Activity implements OnErrorListener, 

OnBufferingUpdateListener,
OnCompletionListener, OnPreparedListener, SurfaceHolder.Callback{

private static final String TAG = "MediaPreview";

private MediaPlayer mp;
private SurfaceView mPreview;
private SurfaceHolder holder;
private Button btnPlay;
private Button btnPause;
private Button btnReset;
private Button btnStop;

private String mPath;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.media_preview);

    mPreview = (SurfaceView)findViewById(R.id.mPreview);
    btnPlay = (Button)findViewById(R.id.btnPlay);
    btnPause = (Button)findViewById(R.id.btnPause);
    btnReset = (Button)findViewById(R.id.btnReset);
    btnStop = (Button)findViewById(R.id.btnStop);

    getPathFromParentDialog();

    btnPlay.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            playVideo();
        }
    });

    btnPause.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            if(mp != null){
                mp.pause();
            }
        }
    });

    btnReset.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            if(mp != null){
                mp.seekTo(0);
            }
        }
    });

    btnStop.setOnClickListener(new View.OnClickListener(){

        @Override
        public void onClick(View v) {
            if(mp != null){
                mp.stop();
                mp.release();
            }
        }
    });

    getWindow().setFormat(PixelFormat.TRANSPARENT);
    holder = mPreview.getHolder();
    holder.addCallback(this);
    holder.setFixedSize(400, 300);
}

@Override
protected void onResume() {

    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
    super.onResume();
}

@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
    if(mp != null){
        mp.stop();
        mp.release();
    }
    return false;
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
    // TODO Auto-generated method stub

}

@Override
public void onCompletion(MediaPlayer mp) {
    // TODO Auto-generated method stub

}

@Override
public void onPrepared(MediaPlayer mp) {
    // TODO Auto-generated method stub

}

@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

}

@Override
public void surfaceDestroyed(SurfaceHolder holder) {
    // TODO Auto-generated method stub

}

private void playVideo() {
    try{
        mp = new MediaPlayer();
        mp.setOnErrorListener(this);
        mp.setOnBufferingUpdateListener(this);
        mp.setOnCompletionListener(this);
        mp.setOnPreparedListener(this);
        mp.setAudioStreamType(2);

        mp.setDisplay(mPreview.getHolder());
        Runnable r = new Runnable(){
            @Override
            public void run() {
                try{
                    setDataSource(mPath);
                }
                catch(Exception ex){
                    Log.e(TAG, ex.getMessage());
                }
                try {
                    mp.prepare();
                    Log.v(TAG, "Duration: ===> " + mp.getDuration());
                } catch (IllegalStateException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    Log.e(TAG, e.getMessage());
                }
                mp.start();
            }

        };
        new Thread(r).start();
    }
    catch(Exception ex){
        String sDummy = ex.toString();
        if(mp != null){
            mp.stop();
            mp.release();
        }
    }

}

private void setDataSource(String path) throws IOException {
    if(!URLUtil.isNetworkUrl(mPath)){
        mp.setDataSource(mPath);
    }
    else{
        URL url = new URL(mPath);
        URLConnection cn = url.openConnection();
        cn.connect();
        InputStream stream = cn.getInputStream();
        if(stream == null){
            throw new RuntimeException("stream is null");
        }
        File fileTemp = File.createTempFile("mediaplayerTmp", "dat");
        String tempPath = fileTemp.getAbsolutePath();
        FileOutputStream out = new FileOutputStream(fileTemp);
        byte buf[] = new byte[128];
        do{
            int numRead = stream.read(buf);
            if(numRead <= 0){
                break;
            }
            out.write(buf, 0, numRead);
        }while(true);
        mp.setDataSource(tempPath);
        try{
            stream.close();
        }
        catch(Exception ex){
            String sDummy = ex.toString();
        }
    }
}

private void getPathFromParentDialog()
{
    Intent intent = getIntent();
    mPath = intent.getExtras().getString(MediaLibrary.FILENAME);
}
}

The code successfully executes (without any exceptions) until mp.start();, but the screen is blank (there are only buttons on the screen).

代码成功执行(没有任何异常)until mp.start();,但屏幕是空白的(屏幕上只有按钮)。

Does anyone know what could be wrong in the code above or is there any example that works available on the web?

有谁知道上面的代码可能有什么问题,或者是否有任何可以在网络上使用的示例?

I would really appreciate your help

我将衷心感谢您的帮助

采纳答案by CommonsWare

Off the cuff, I think you need some more logic in some of your callback methods, like surfaceCreated().

袖手旁观,我认为您在某些回调方法中需要更多逻辑,例如surfaceCreated().

回答by sathya

You need to attach the surface to the played after the surface is created.

创建表面后,您需要将表面附加到播放的对象上。

call

称呼

 mp.setDisplay(mPreview.getHolder());

from inside

从内部

public void surfaceCreated(SurfaceHolder holder)