使用Vitamio開源專案在Android實現播放網路視訊

ghsbsr發表於2015-05-29

Vitamio是一款開源的視訊播放庫,我們可以在Android或者ios中很輕鬆的呼叫。本文主要介紹瞭如何在AndroidStudio中匯入Vitamio庫,以實現播放網路視訊。

一,匯入Vitamio工程

1,去GitHub下載這個專案: https://github.com/yixia/VitamioBundle

2,在AndroidStudio中將其匯入


如圖,我們選擇Import Module(在AndroidStudio中一個Project就相當於Eclipse中的WorkSpace,而Module則相當於Eclipse中的Project)。


如圖在這裡將專案匯入我們的專案中。

3,將匯入的Vitamio專案作為一個庫引用


如圖,我們選擇Project Structure,然後在彈出的頁面的左邊的Modules一欄,選擇我們的主要的Android專案,然後點選右邊Dependencies一欄,點選底部的“加號”如下圖,並選擇Module dependency。


在彈出的介面中,我們選擇剛剛匯入的Vitamio工程,然後點選ok,即可匯入成功。

二,使用Vitamio建立自己的播放器Activity

public class VideoViewBuffer extends Activity implements MediaPlayer.OnInfoListener, MediaPlayer.OnBufferingUpdateListener {

    /**
     * TODO: Set the path variable to a streaming video URL or a local media file
     * path.
     */
    private String path = "測試視訊地址";
    private Uri uri;
    private io.vov.vitamio.widget.VideoView mVideoView;
    private ProgressBar pb;
    private TextView downloadRateView, loadRateView;
    private String subTitleUrlPath = "字幕地址";
    private String subTitlePath = Environment.getExternalStorageDirectory() + "/Test/";
    private String subTitleName = "test.srt";
    private TextView tvSrt;
    private List<HashMap<String, String>> SrtList;
    private DownLoadSubTitle task = new DownLoadSubTitle();
    private SrtTask srtTask = new SrtTask();

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        if (!LibsChecker.checkVitamioLibs(this))
            return;
        setContentView(R.layout.coursera_videobuffer);
        mVideoView = (VideoView) findViewById(R.id.buffera);
        pb = (ProgressBar) findViewById(R.id.probar);

        downloadRateView = (TextView) findViewById(R.id.download_rate);
        loadRateView = (TextView) findViewById(R.id.load_rate);

        tvSrt = (TextView) findViewById(R.id.coursera_videobuffer_srt);//專案中顯示字幕的控制元件
        if (path == "") {
            // Tell the user to provide a media file URL/path.
            Toast.makeText(
                    VideoViewBuffer.this,
                    "Please edit VideoBuffer Activity, and set path"
                            + " variable to your media file URL/path", Toast.LENGTH_LONG).show();
            return;
        } else {
      /*
       * Alternatively,for streaming media you can use
       * mVideoView.setVideoURI(Uri.parse(URLstring));
       */
            uri = Uri.parse(path);
            mVideoView.setVideoURI(uri);
            mVideoView.setMediaController(new MediaController(this, mVideoView));
            mVideoView.requestFocus();
            mVideoView.setOnInfoListener(this);
            mVideoView.setOnBufferingUpdateListener(this);
            mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    // optional need Vitamio 4.0
                    task.execute();
                    mediaPlayer.setPlaybackSpeed(1.0f);
                }
            });
        }
//    Toast.makeText(getApplicationContext(), "測試", Toast.LENGTH_SHORT).show();

    }

    @Override
    public boolean onInfo(MediaPlayer mp, int what, int extra) {
        switch (what) {
            case MediaPlayer.MEDIA_INFO_BUFFERING_START:
                if (mVideoView.isPlaying()) {
                    mVideoView.pause();
                    pb.setVisibility(View.VISIBLE);
                    downloadRateView.setText("");
                    loadRateView.setText("");
                    downloadRateView.setVisibility(View.VISIBLE);
                    loadRateView.setVisibility(View.VISIBLE);
                }
                break;
            case MediaPlayer.MEDIA_INFO_BUFFERING_END:
                mVideoView.start();
                pb.setVisibility(View.GONE);
                downloadRateView.setVisibility(View.GONE);
                loadRateView.setVisibility(View.GONE);
                break;
            case MediaPlayer.MEDIA_INFO_DOWNLOAD_RATE_CHANGED:
                downloadRateView.setText("" + extra + "kb/s" + "  ");
                break;
        }
        return true;
    }

    @Override
    public void onBufferingUpdate(MediaPlayer mp, int percent) {
        loadRateView.setText(percent + "%");
    }

    public void onConfigurationChanged(Configuration newConfig) {
//        System.out.println("方向變化了");
        mVideoView.setVideoLayout(mVideoView.mVideoLayout, mVideoView.mAspectRatio);
        super.onConfigurationChanged(newConfig);
//        System.out.println("videoBuffer中的方向" + newConfig.orientation);
    }

    public void getSubtitle(String path, String filename) {
        HttpDownLoad hd = new HttpDownLoad();
        hd.getConnection(path);
        if ((hd.getInputStream() != null) && (hd.getLength() != 0)) {
            hd.writeIntoSD(filename);
        }
    }

    private class DownLoadSubTitle extends AsyncTask<Integer, Integer, Integer> {

        @Override
        protected Integer doInBackground(Integer... params) {
            System.out.println("執行了下載字幕的方法");
            int state = 0;
            try {
                getSubtitle(subTitleUrlPath, subTitleName);
            } catch (Exception e) {
                state = 1;
                e.printStackTrace();
            }
            return state;
        }

        @Override
        protected void onPostExecute(Integer result) {
            if (result == 0) {
                showSrt(subTitlePath + subTitleName);
                System.out.println("執行了下載字幕的方法,成功");
            } else {
                Toast.makeText(getApplicationContext(), "字幕獲取失敗", Toast.LENGTH_SHORT).show();
            }
        }
    }

    private void showSrt(String filePath) {
        tvSrt.setVisibility(View.VISIBLE);
        SrtUtils srt = new SrtUtils();
        srt.loadLyricFile(filePath);
        SrtList = srt.getSrtList();
        srtTask.execute();
    }

    private class SrtTask extends AsyncTask<Integer, Integer, Integer> {
        private int position;
        private String currentTex = "";

        @Override
        protected Integer doInBackground(Integer... params) {
            while (mVideoView.getCurrentPosition() < mVideoView.getDuration()) {
                if (isCancelled()) {
                    return null;
                }
                for (int i = 0; i < SrtList.size(); i++) {
                    HashMap map = SrtList.get(i);
                    long start = Long.parseLong(map.get("start").toString());
                    long end = Long.parseLong(map.get("end").toString());
                    long current = mVideoView.getCurrentPosition();
                    if ((current > start && current < end)) {
                        position = i;
                        publishProgress(i);
                    }
                }
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            return null;
        }

        @Override
        protected void onProgressUpdate(Integer... values) {
            if (isCancelled()) {
                return;
            }
            String tex = SrtList.get(position).get("text").toString();
            if (currentTex.equals("")) {
                tvSrt.setText(tex);
            } else {
                if (!currentTex.equals(tex)) {
                    tvSrt.setText(tex);
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        System.out.println("重寫了onDestory方法");
        task.cancel(true);
        srtTask.cancel(true);
    }

    @Override
    public void onBackPressed() {
        System.out.println("重寫了back方法");
        task.cancel(true);
        srtTask.cancel(true);
        this.finish();
        return;
    }
}



相關文章