一.MediaPlayer

Android的MediaPlayer包含了Audio和video的播放功能,在Android的界面上,Music和Video两个应用程序都是调用MediaPlayer实现的
MediaPlayer在底层是基于OpenCore(PacketVideo)的库实现的

二.创建MediaPlayer实例

1:MediaPlayer mp = new MediaPlayer();
mp.setDataSource("/sdcard/test.mp3");
2:MediaPlayer mp = MediaPlayer.create(this, R.raw.test);

三.MediaPlayer API

Android通过控制播放器的状态的方式来控制媒体文件的播放

prepare()和prepareAsync() 提供了同步和异步两种方式设置播放器进入prepare状态,需要注意的是,如果MediaPlayer实例是由create方法创建的,那么第一次启动播放前不需要再调用prepare()了,因为create方法里已经调用过了。

start()是真正启动文件播放的方法, pause()和stop()比较简单,起到暂停和停止播放的作用,
seekTo()是定位方法,可以让播放器从指定的位置开始播放,需要注意的是该方法是个异步方法,也就是说该方法返回时并不意味着定位完成,尤其是播放的网络文件,真正定位完成时会触发OnSeekComplete.onSeekComplete(),如果需要是可以调用setOnSeekCompleteListener(OnSeekCompleteListener)设置监听器来处理的。

release()可以释放播放器占用的资源,一旦确定不再使用播放器时应当尽早调用它释放资源。

reset()可以使播放器从Error状态中恢复过来,重新会到Idle状态。

四.例子,代码

4.1播放音乐

public class PlayMusicActivity extends Activity {

    private SeekBar sb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_music);
        sb=(SeekBar)findViewById(R.id.sb);
        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(mp!=null)
                    mp.seekTo(seekBar.getProgress());
            }
        });
    }

    //播放音乐
    MediaPlayer mp;
    boolean isRun=true;
    public void doPlay(View view){
        if(mp!=null)
            return;
        isRun=true;
        mp=new MediaPlayer();//构建一个播放器对象
        mp.reset();//点击播放重置
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/nobody.mp3";//歌曲的路径
        try {
            mp.setDataSource(path);//设置要播放的文件路径
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);//设置多媒体类型
            mp.prepare();//准备就绪
            sb.setMax(mp.getDuration());//设置进度条最大值为音频文件的持续时间
            mp.start();//开始播放

            //更新进度
            new Thread(new Runnable() {
                @Override
                public void run() {
                    while(isRun&&mp.getCurrentPosition()<=sb.getMax()){
                        sb.setProgress(mp.getCurrentPosition());
                        SystemClock.sleep(200);
                    }
                }
            }).start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doPause(View view){
        if(mp==null)
            return;
        if(mp.isPlaying()){
            mp.pause();
            ((Button)view).setText("继续播放");
        }else{
            mp.start();
            ((Button)view).setText("暂停");
        }
    }

    public void doStop(View view){
        if(mp!=null&&mp.isPlaying()){
            isRun=false;
            mp.stop();
            mp.release();
            mp=null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doStop(null);
    }
}

 

 4.2播放视频

1.方法一:

//播放视频一
    public void playVedio_1(View view){
        Intent intent=new Intent(Intent.ACTION_VIEW);
        Uri uri= Uri.parse("file:///sdcard/goodmm.mp4");//更换为你自己的路径
        intent.setDataAndType(uri,"video/mp4");
        startActivity(intent);
    }

 

 2.方法二:

//播放视频二
    public void playVedio_2(View view){
        Intent intent=new Intent(this,PlayVideoActivity.class);
        startActivity(intent);
    }

 

 

public class PlayVideoActivity extends Activity {

    private VideoView videoView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video);
        videoView=(VideoView)findViewById(R.id.videoView);
        videoView.setMediaController(new MediaController(this));
        Uri uri= Uri.parse("file:///sdcard/goodmm.mp4");
        videoView.setVideoURI(uri);
        new Thread(new Runnable() {
            @Override
            public void run() {
                SystemClock.sleep(5000);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        videoView.setBackground(null);
                        videoView.start();
                    }
                });
            }
        }).start();
    }
}

 

 3.方法三:

//播放视频三
    public void playVedio_3(View view){
        Intent intent=new Intent(this,PlayVideo_2Activity.class);
        startActivity(intent);
    }

 

 

public class PlayVideo_2Activity extends Activity {

    private MediaPlayer mp;
    private SurfaceView sfView;
    private SurfaceHolder holder;
    private SeekBar sb;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_play_video_2);

        sb=(SeekBar)findViewById(R.id.sb);
        sfView=(SurfaceView)findViewById(R.id.sfView);
        holder=sfView.getHolder();

        sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
            }
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
            }
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                if(mp!=null)
                    mp.seekTo(seekBar.getProgress());
            }
        });
    }

    boolean isRun=true;
    public void doPlay(View view){
        if(mp!=null)
            return;
        isRun=true;
        mp=new MediaPlayer();
        mp.reset();
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/goodmm.mp4";
        try {
            mp.setDataSource(path);//设置数据源
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDisplay(holder);//设置显示位置
            mp.prepare();
            sb.setMax(mp.getDuration());
            sfView.setBackground(null);
            mp.start();

            new Thread(new Runnable() {
                @Override
                public void run() {
                    while (isRun&&mp.getCurrentPosition()<=sb.getMax()){
                        sb.setProgress(mp.getCurrentPosition());
                        SystemClock.sleep(200);
                    }
                }
            }).start();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doPause(View view){
        if(mp==null)
            return;
        if(mp.isPlaying()){
            mp.pause();
            ((Button)view).setText("继续播放");
        }else{
            mp.start();
            ((Button)view).setText("暂停");
        }
    }

    public void doStop(View view){
        if(mp!=null&&mp.isPlaying()){
            isRun=false;
            mp.stop();
            mp.release();
            mp=null;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doStop(null);
    }


}

 

 4.3录制

MediaRecorder:

Android的MediaRecorder包含了Audio和video的记录功能,在Android的界面上,Music和Video两个应用程序都是调用MediaRecorder实现的。 
MediaRecorder在底层是基于OpenCore(PacketVideo)的库实现的。

4.3.1录制音频并播放

//录制音频
public
void recorder_test(View view){ Intent intent=new Intent(this,RecorderActivity.class); startActivity(intent); }

 

public class RecorderActivity extends Activity {

    private MediaRecorder recorder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder);
    }

    //开始录音
    public void doStart(View view){
        if(recorder!=null)
            return;
        recorder=new MediaRecorder();//构建了一个录音设备
        recorder.setAudioSource(MediaRecorder.AudioSource.MIC);//设置声音来源
        recorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);//设置录音文件格式
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);//设置声音编码类型
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luyin.3gp";
        recorder.setOutputFile(path);//设置输出文件位置
        try {
            recorder.prepare();//录音设备就绪
            recorder.start();//开始录音
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //录音结束
    public void doStop(View view){
        if(recorder!=null){
            recorder.stop();
            recorder.release();
            recorder=null;
        }
    }

    //播放录音
    MediaPlayer mp;
    public void doPlay(View view){
        if(mp!=null)
            return;
        mp=new MediaPlayer();
        mp.reset();
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luyin.3gp";
        try {
            mp.setDataSource(path);
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        doStop(null);
    }
}

 

4.3.2录制视频并播放

//录制视频
    public void recorder_video_test(View view){
        Intent intent=new Intent(this,Recorder_VideoActivity.class);
        startActivity(intent);
    }

 

public class Recorder_VideoActivity extends Activity {

    private MediaPlayer mp;
    private SurfaceView sfView;
    private SurfaceHolder holder;
    private MediaRecorder recorder;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_recorder__video);
        sfView=(SurfaceView)findViewById(R.id.sfView);
        holder=sfView.getHolder();
    }

    //开始录像
    public void doStart(View view){
        recorder=new MediaRecorder();
        recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        recorder.setVideoEncoder(MediaRecorder.VideoEncoder.DEFAULT);
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luxiang.mp4";
        recorder.setOutputFile(path);
        recorder.setPreviewDisplay(holder.getSurface());
        try {
            recorder.prepare();
            recorder.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void doStop(View view){
        if(recorder!=null){
            try{
                recorder.stop();
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }

    }

    public void doPlay(View view){
        if(mp!=null)
            return;
        mp=new MediaPlayer();
        mp.reset();
        String path= Environment.getExternalStorageDirectory().getAbsolutePath()+"/luxiang.mp4";
        try {
            mp.setDataSource(path);//设置数据源
            mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mp.setDisplay(holder);//设置显示位置
            mp.prepare();
            sfView.setBackground(null);
            mp.start();
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }
}