android视频播放的代码

本地视频播放,包括播放、暂停,继续等,还有显示播放的进度。效果如下:

android视频播放的代码_第1张图片

1.activity_main.xml




    
      


2.MainActivity.java

package com.zhang.videoplay;

import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;


public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private Button plastart, pause, playstop, rebroadcast;
    private SurfaceView surfaceView;
    private SeekBar seekBar;
    private MediaPlayer mediaPlayer;
    private int currentPosition = 0;
    private boolean isPlaying;

    private TextView startTime,sumTime;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        initView();
        // 为SurfaceHolder添加回调
        surfaceView.getHolder().addCallback(callback);
        // 设置Surface不维护自己的缓冲区,而是等待屏幕的渲染引擎将内容推送到界面
        surfaceView.getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        // 为进度条添加进度更改事件
        seekBar.setOnSeekBarChangeListener(change);
    }

    private void initView() {
        plastart = (Button) findViewById(R.id.playstart);
        plastart.setOnClickListener(this);

        pause = (Button) findViewById(R.id.pause);
        pause.setOnClickListener(this);

        playstop = (Button) findViewById(R.id.playstop);
        playstop.setOnClickListener(this);

        rebroadcast = (Button) findViewById(R.id.rebroadcast);
        rebroadcast.setOnClickListener(this);

        sumTime= (TextView) findViewById(R.id.sumTime);
        startTime= (TextView) findViewById(R.id.startime);
        surfaceView = (SurfaceView) findViewById(R.id.surfaceView);
        seekBar = (SeekBar) findViewById(R.id.seekBar);
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {

            case R.id.playstart://开始
                play(0);
                plastart.setEnabled(false);
                break;
            case R.id.playstop://停止
                stop();
                break;
            case R.id.rebroadcast://重播
                replay();
                break;
            case R.id.pause://暂停
                pause();
                break;
        }

    }

     // 添加一个Callback对象监听SurfaceView的变化
    private Callback callback = new Callback() {
        // SurfaceHolder被修改的时候回调
        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            Log.i("info", "SurfaceHolder 被销毁");
            // 销毁SurfaceHolder的时候记录当前的播放位置并停止播放
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                currentPosition = mediaPlayer.getCurrentPosition();
                mediaPlayer.stop();
            }
        }

         //SurfaceView创建时触发
        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            Log.i("info", "SurfaceHolder 被创建");
            if (currentPosition > 0) {
                // 创建SurfaceHolder的时候,如果存在上次播放的位置,则按照上次播放位置进行播放
                play(currentPosition);
                currentPosition = 0;
            }
        }

         //SurfaceView改变时触发
        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int width,
                                   int height) {
            Log.i("info", "SurfaceHolder 大小被改变");
        }
    };

    private OnSeekBarChangeListener change = new OnSeekBarChangeListener() {

        @Override
        public void onStopTrackingTouch(SeekBar seekBar) {
            // 当进度条停止修改的时候触发
            // 取得当前进度条的刻度
            int progress = seekBar.getProgress();
            if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                // 设置当前播放的位置
                mediaPlayer.seekTo(progress);

            }
        }

        @Override
        public void onStartTrackingTouch(SeekBar seekBar) {

        }

        @Override
        public void onProgressChanged(SeekBar seekBar, int progress,
                                      boolean fromUser) {
            Log.i("info","onStopTrackingTouch--"+progress);
            shiftTime(startTime,progress);
        }
    };


    /**
     * 开始播放
     *
     * @param msec 播放初始位置
     */
    protected void play(final int msec) {
        // 获取视频文件地址
        String path = "/storage/emulated/0/Download/video.mp4";
        File file = new File(path);
        if (!file.exists()) {
            Toast.makeText(this, "视频文件路径错误", Toast.LENGTH_LONG).show();

            return;
        }
        try {
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            // 设置播放的视频源
            Log.i("info", "1111111" + file.getAbsolutePath());
            mediaPlayer.setDataSource(file.getAbsolutePath());
            // 设置显示视频的SurfaceHolder,指定视频画面输出到SurfaceView之上
            mediaPlayer.setDisplay(surfaceView.getHolder());
            Log.i("info", "开始装载");
            mediaPlayer.prepareAsync();
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

                @Override
                public void onPrepared(MediaPlayer mp) {
                    Log.i("info", "装载完成");
                    mediaPlayer.start();
                    // 按照初始位置播放
                    mediaPlayer.seekTo(msec);
                    // 设置进度条的最大进度为视频流的最大播放时长
                    seekBar.setMax(mediaPlayer.getDuration());
                    Log.i("info","2222222222-----"+mediaPlayer.getDuration());
                    //将刻度转换成时间mm:ss
                    shiftTime(sumTime,mediaPlayer.getDuration());
                    // 开始线程,更新进度条的刻度
                    new Thread() {

                        @Override
                        public void run() {
                            try {
                                isPlaying = true;
                                while (isPlaying) {
                                    int current = mediaPlayer
                                            .getCurrentPosition();
                                    seekBar.setProgress(current);
                                    sleep(1000);

                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }.start();
                   //将停止按钮设置不可点击
                    playstop.setEnabled(false);
                }
            });

            mediaPlayer.setOnCompletionListener(new OnCompletionListener() {

                @Override
                public void onCompletion(MediaPlayer mp) {
                    // 在播放完毕被回调
                    playstop.setEnabled(true);
                }
            });

            mediaPlayer.setOnErrorListener(new OnErrorListener() {

                @Override
                public boolean onError(MediaPlayer mp, int what, int extra) {
                    // 发生错误重新播放
                    Log.i("info","onError---"+what);
                    play(0);
                    isPlaying = false;
                    return false;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 重新开始播放
     */
    protected void replay() {
        if (mediaPlayer != null&& mediaPlayer.isPlaying()){
            mediaPlayer.seekTo(0);
            Toast.makeText(this,"重新播放",Toast.LENGTH_LONG).show();
            pause.setText("暂停");
            return;
        }
        play(0);
        isPlaying = false;


    }

    /**
     * 暂停或继续
     */
    protected void pause() {
        if (pause.getText().toString().trim().equals("继续")) {
            pause.setText("暂停");
            mediaPlayer.start();
            Toast.makeText(this, "继续播放", Toast.LENGTH_SHORT).show();
            return;
        }
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            pause.setText("继续");
            Toast.makeText(this,"暂停播放",Toast.LENGTH_SHORT).show();
        }

    }

    /**
     * 停止播放
     */
    protected void stop() {

        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
            playstop.setEnabled(true);
            isPlaying = false;
        }
    }

    //将刻度转换为时间

    private void shiftTime(TextView view,int time){
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("mm:ss");
        date.setTime(time);
        String str = sdf.format(date);
        Log.i("info","33333333-----"+str);
        view.setText(str);
    }

}



3.加入权限

 
    
    
    





你可能感兴趣的:(android视频播放的代码)