Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> 關於Android編程 >> android視頻播放的代碼

android視頻播放的代碼

編輯:關於Android編程

\

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.加入權限

 
    
    
    

 
 
  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved