Android萬能視頻播放器-移植第三方庫(vitamio)

        我們知道,Android中MediaPlayer和VedioView能夠播放視頻文件,但是其支持的格式僅限於mp4與3gb。但是視頻格式如此之多,我們不可能只要求播放這兩種,所以就有了下文。
        目前比較出名的第三方庫有vitanio與VLC,其中vitamio使用非常簡單,讓開發者直接以library的形式導入工程即可使用,代碼極其簡單;而VLC相比之下就困難的多了。
所以在這裏選擇相對簡單的vitamio第三方庫,而且能夠支持幾乎是全部格式的視頻,非常棒。
         vitamio官網

 官方demo演示效果:

Vitamio支持各種常見的流媒體協議,可以點播或者直播音頻和視頻,例如如下常見協議均能無縫支持:
  • MMS
  • RTSP (RTP, SDP), RTMP
  • HTTP progressive streaming
  • HLS - HTTP live streaming (M3U8)

音頻和視頻格式

Vitamio使用了 FFmpeg 做爲媒體解析器和最主要的解碼器,同時開發了針對不同移動平臺的硬解碼方案,能夠完美支持 H.264/AVC、H.263、MPEG4 等常見的視頻編碼,覆蓋上百種多媒體格式。下表只是一些最常見的視頻格式支持,除特殊標明,全部支持硬件加速:
  • DivX/Xvid
  • WMV (一般只有軟解碼)
  • FLV
  • TS/TP
  • RMVB (只有軟解碼)
  • MKV
  • MOV
  • M4V
  • AVI
  • MP4
  • 3GP

一、重寫的MediaPlayer播放效果:

二、重寫的VedioView播放效果


移植到自己的工程之後的效果

一、MediaPlayer演示效果

二、VedioView移植效果

                                                                                                                                          移植過程

一、從官網下載下來的demo打開後是,只有vitamio(庫)和vitamia-sample(使用demo)有用。

二、將官方工程(InitActivity庫+VitamioListActivity例子)導入eclipse,以及建立自己要移植額工程(tieniu_demo)。


三、將InitActivity庫導入我們的工程


四、修改代碼


MainActivity.java
package com.example.vitamia_demo;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.view.Menu;
import android.view.MenuItem;


public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.media) {
			Intent intent = new Intent(MainActivity.this,Media.class);
			intent.putExtra("video_path", Environment.getExternalStorageDirectory().getAbsolutePath() + "/Moon.mp4");//SD卡更目錄下放一個
			startActivity(intent);
            return true;
        }
        if (id == R.id.vedio) {
			Intent intent2 = new Intent(MainActivity.this,VedioView.class);
			intent2.putExtra("video_path", Environment.getExternalStorageDirectory().getAbsolutePath() + "/Moon.mp4");<span style="font-family: Arial, Helvetica, sans-serif;">//SD卡更目錄下放該視頻</span>
			startActivity(intent2);
            return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
Media.java
package com.example.vitamia_demo;



/*
 * Copyright (C) 2013 yixia.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import android.app.Activity;
import android.content.Intent;
import android.graphics.PixelFormat;
import android.media.AudioManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.MediaPlayer.OnBufferingUpdateListener;
import io.vov.vitamio.MediaPlayer.OnCompletionListener;
import io.vov.vitamio.MediaPlayer.OnPreparedListener;
import io.vov.vitamio.MediaPlayer.OnVideoSizeChangedListener;

public class Media extends Activity implements OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback {

	private static final String TAG = "MediaPlayerDemo";
	private int mVideoWidth;
	private int mVideoHeight;
	private MediaPlayer mMediaPlayer;
	private SurfaceView mPreview;
	private SurfaceHolder holder;
	private String path;
	private boolean mIsVideoSizeKnown = false;
	private boolean mIsVideoReadyToBePlayed = false;

	/**
	 * 
	 * Called when the activity is first created.
	 */
	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		if (!LibsChecker.checkVitamioLibs(this))
			return;
		setContentView(R.layout.media);
		mPreview = (SurfaceView) findViewById(R.id.surface);
		holder = mPreview.getHolder();
		holder.addCallback(this);
		holder.setFormat(PixelFormat.RGBA_8888);
		//獲得前一個界面傳來的視頻路徑
		Intent mIntent = getIntent();
	    path = mIntent.getStringExtra("video_path");
	    Log.e("path2",path);
	}

	private void playVideo() {
		doCleanUp();
		try {
			// Create a new media player and set the listeners
			mMediaPlayer = new MediaPlayer(this);
			Log.e("load","load");
			mMediaPlayer.setDataSource(path);
			Log.e("load","load2");
			mMediaPlayer.setDisplay(holder);
			Log.e("load","load3");
			mMediaPlayer.prepareAsync();
			Log.e("load","load4");
			mMediaPlayer.setOnBufferingUpdateListener(this);
			Log.e("load","load5");
			mMediaPlayer.setOnCompletionListener(this);
			Log.e("load","load6");
			mMediaPlayer.setOnPreparedListener(this);
			Log.e("load","load7");
			mMediaPlayer.setOnVideoSizeChangedListener(this);
			Log.e("load","load8");
			setVolumeControlStream(AudioManager.STREAM_MUSIC);
			Log.e("load","load9");

		} catch (Exception e) {
			Log.e(TAG, "error: " + e.getMessage(), e);
		}
	}

	public void onBufferingUpdate(MediaPlayer arg0, int percent) {
		// Log.d(TAG, "onBufferingUpdate percent:" + percent);

	}

	public void onCompletion(MediaPlayer arg0) {
		Log.d(TAG, "onCompletion called");
	}

	public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
		Log.v(TAG, "onVideoSizeChanged called");
		if (width == 0 || height == 0) {
			Log.e(TAG, "invalid video width(" + width + ") or height(" + height + ")");
			return;
		}
		mIsVideoSizeKnown = true;
		mVideoWidth = width;
		mVideoHeight = height;
		if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
			startVideoPlayback();
		}
	}

	public void onPrepared(MediaPlayer mediaplayer) {
		Log.d(TAG, "onPrepared called");
		mIsVideoReadyToBePlayed = true;
		if (mIsVideoReadyToBePlayed && mIsVideoSizeKnown) {
			startVideoPlayback();
		}
	}

	public void surfaceChanged(SurfaceHolder surfaceholder, int i, int j, int k) {
		Log.d(TAG, "surfaceChanged called");

	}

	public void surfaceDestroyed(SurfaceHolder surfaceholder) {
		Log.d(TAG, "surfaceDestroyed called");
	}

	public void surfaceCreated(SurfaceHolder holder) {
		Log.d(TAG, "surfaceCreated called");
		Log.e("playvideo","playvideo");
		playVideo();

	}

	@Override
	protected void onPause() {
		super.onPause();
		releaseMediaPlayer();
		doCleanUp();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		releaseMediaPlayer();
		doCleanUp();
	}

	private void releaseMediaPlayer() {
		if (mMediaPlayer != null) {
			mMediaPlayer.release();
			mMediaPlayer = null;
		}
	}

	private void doCleanUp() {
		mVideoWidth = 0;
		mVideoHeight = 0;
		mIsVideoReadyToBePlayed = false;
		mIsVideoSizeKnown = false;
	}

	private void startVideoPlayback() {
		Log.v(TAG, "startVideoPlayback");
		/*
		WindowManager windowManager = getWindowManager();
        Display display = windowManager.getDefaultDisplay();
		holder.setFixedSize(display.getWidth(), display.getHeight());
		*/
		holder.setFixedSize(mVideoWidth, mVideoHeight);
		
		mMediaPlayer.start();
	}
}
VedioView.java
package com.example.vitamia_demo;


/*
 * Copyright (C) 2013 yixia.com
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
import io.vov.vitamio.LibsChecker;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.widget.MediaController;
import io.vov.vitamio.widget.VideoView;

public class VedioView extends Activity {

	/**
	 * TODO: Set the path variable to a streaming video URL or a local media file
	 * path.
	 */
	private String path = "";
	private VideoView mVideoView;

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);
		if (!LibsChecker.checkVitamioLibs(this))
			return;
		setContentView(R.layout.videoview);
		mVideoView = (VideoView) findViewById(R.id.surface_view);
		Intent mIntent = getIntent();
	    path = mIntent.getStringExtra("video_path");
		if (path == "") {
			// Tell the user to provide a media file URL/path.
			Toast.makeText(VedioView.this, "Please edit VideoViewDemo 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));
			 */
			mVideoView.setVideoPath(path);
			mVideoView.setMediaController(new MediaController(this));
			mVideoView.requestFocus();

			mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
				@Override
				public void onPrepared(MediaPlayer mediaPlayer) {
					// optional need Vitamio 4.0
					mediaPlayer.setPlaybackSpeed(1.0f);
				}
			});
		}

	}

	
	public void openVideo(View View) {
	  mVideoView.setVideoPath(path);
	}
	
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.vitamia_demo.MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

</RelativeLayout>
media.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <io.vov.vitamio.widget.CenterLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical" >

        <SurfaceView
            android:id="@+id/surface"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center" >
        </SurfaceView>
    </io.vov.vitamio.widget.CenterLayout>

</LinearLayout>
vedioview.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
   
    <io.vov.vitamio.widget.VideoView
        android:id="@+id/surface_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" /> 

</LinearLayout>
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.vitamia_demo"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="14"
        android:targetSdkVersion="21" />
    <uses-permission android:name="android.permission.WAKE_LOCK" />
    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <!-- Don't forgot InitActivity -->
        <activity
            android:name="io.vov.vitamio.activity.InitActivity"
            android:configChanges="orientation|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation"
            android:launchMode="singleTop"
            android:theme="@android:style/Theme.NoTitleBar"
            android:windowSoftInputMode="stateAlwaysHidden" />
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".VedioView"
            android:configChanges="orientation|screenSize|smallestScreenSize|keyboard|keyboardHidden|navigation">
        </activity>
         <activity
            android:name=".Media">
        </activity>
    </application>

</manifest>

完整工程(包含官網SDK以及移植的工程)下載地址



發佈了35 篇原創文章 · 獲贊 7 · 訪問量 8萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章