MediaPlayer: MediaPlayer中的prepare方法和prepareAsync方法的区别

  prepare方法是将资源同步缓存到内存中,一般加载本地较小的资源可以用这个,如果是较大的资源或者网络资源建议使用prepareAsync方法,异步加载.但如果想让资源启动,即start()起来,因为在异步中,如果不设置监听直接start的话,是拿不到这个资源,如果让线程睡眠一段时间,则可以取得资源,因为这个时候,异步线程已经取得资源,但不可能使用线程睡眠的方式来获取资源啊.所以就需要设置监听事件setOnPreparedListener();来通知MediaPlayer资源已经获取到了,然后实现onPrepared(MediaPlayer mp)方法.在里面启动MediaPlayer。例:

package com.kira.surfaceviewforvideo;
 
import java.io.File;
import java.io.IOException;
 
import android.app.Activity;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.SystemClock;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
 
public class MainActivity extends Activity implements Callback,
        OnPreparedListener {
 
    private SurfaceView sv;
    private SurfaceHolder holder1;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sv = (SurfaceView) findViewById(R.id.surface);
        holder1 = sv.getHolder();
        holder1.addCallback(this);
    }
 
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        // TODO Auto-generated method stub
        // 播放视频
        MediaPlayer media = new MediaPlayer();
        // 缓存到内存
        File file = new File(Environment.getExternalStorageDirectory(),
                "oppo.3gp");
        try {
            media.setDataSource(file.getAbsolutePath());
            // 异步缓存到内存
            // media.prepare();
 
            media.prepareAsync();
            //SystemClock.sleep(5000); // 若让其睡眠5秒钟,则可以prepareAsync可以取到资源
            media.setOnPreparedListener(this);
            // media.prepare();
            media.setDisplay(holder);
            media.start();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
 
    }
 
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
            int height) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        // TODO Auto-generated method stub
 
    }
 
    @Override
    public void onPrepared(MediaPlayer mp) {
        // TODO Auto-generated method stub
         mp.start(); // 在这里启动MediaPlayer
    }
 
}

 

上一篇:unexpected character found (0) in ‘reader‘, line 19, column 19: include: *


下一篇:spring-boot 监控 Actuator