对于IOS平台的视频播放,我们可以借助Cocos2d-iphone 的Extensions:CCVideoPlayer来实现
1.导入支持cocos2d-x的扩展库到项目中(这里可以参考Himi的第六章视频播放小节内容,这里的扩展库是Himi修改好的,我就直接拿来用了!希望没有侵权!)
2.添加MediaPalyer框架到项目中
3.修改ios里AppController.h 和AppController.mm文件
AppController.h
- #import"../Classes/CCVideoPlayeriOS/CCVideoPlayer.h"
- @classRootViewController;
- @interfaceAppController:NSObject<UIAccelerometerDelegate,UIAlertViewDelegate,
- UITextFieldDelegate,UIApplicationDelegate,CCVideoPlayerDelegate>
- {
- UIWindow*window;
- RootViewController*viewController;
- }
- @property(nonatomic,retain)UIWindow*window;
- @property(nonatomic,retain)RootViewController*viewController;
- -(void)playVideo;
- @end
AppController.mm
添加using namespace cocos2d;
因为playVideo用到了cocos2d-x里的api
CCSizesize = CCDirector::sharedDirector()->getWinSize();
在application函数里添加视频播放监听
[CCVideoPlayer setDelegate :self];
playVideo实现如下:
- -(void)playVideo
- {
- CCSizesize=CCDirector::sharedDirector()->getWinSize();
- [CCVideoPlayersetScrrenSize:CGSizeMake(size.width-400,size.height-300)];
- [CCVideoPlayersetNoSkip:true];
- [CCVideoPlayerplayMovieWithFile:@"xcm.mp4"];
- //播放网络视频
- //[viewControllerplayURLVideo];
- }
4.添加混编类IOSPlayVideo
IOSPlayVideo.h
- #ifndef__IOSPlayVideo_SCENE_H__
- #define__IOSPlayVideo_SCENE_H__
- classIOSPlayVideo
- {
- public:
- staticvoidplayVideoForIOS();
- };
- #endif//__IOSPlayVideo_SCENE_H__
IOSPlayVideo.mm
- #include"IOSPlayVideo.h"
- #include"AppController.h"
- voidIOSPlayVideo::playVideoForIOS()
- {
- AppController*app=(AppController*)[[UIApplicationsharedApplication]delegate];
- [appplayVideo];
- }
5.添加一个cocos2d-x类 :Platform
Platform.h
- #ifndef__Platform_SCENE_H__
- #define__Platform_SCENE_H__
- #include"cocos2d.h"
- usingnamespacecocos2d;
- classPlatform
- {
- public:
- staticvoidplayVideo();//用于播放本地视频
- staticvoidplayURLVideo();//用于播放网络视频
- };
- #endif//__Platform_SCENE_H__
Platform.mm
- #include"Platform.h"
- #include"../cocos2dx/platform/CCPlatformConfig.h"
- #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
- #include<jni.h>
- #include"../cocos2dx/platform/android/jni/JniHelper.h"
- #include<android/log.h>
- #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
- #include"IOSPlayVideo.h"
- #endif
- voidPlatform::playVideo()
- {
- #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
- //Android播放本地视频
- JniMethodInfominfo;
- boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/playvideo/playvideo","playVedio","()V");
- if(isHave)
- {
- minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
- }
- #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
- //IOS播放本地视频
- IOSPlayVideo::playVideoForIOS();
- #endif
- }
- voidPlatform::playURLVideo()
- {
- #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
- //Android播放网络视频
- JniMethodInfominfo;
- boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/playvideo/playvideo","playURLVideo","()V");
- if(isHave)
- {
- minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
- }
- #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
- //IOS播放网络视频
- IOSPlayVideo::playVideoForIOS();
- #endif
- }
IOS项目里只需在需要的地方调用函数就可以播放视频了!
至于Android就稍微麻烦一点,需要用到Jni 技术, C++调用java
A.修改playvideo.java
修改后如下:
- packageorg.cocos2dx.playvideo;
- importorg.cocos2dx.lib.Cocos2dxActivity;
- importorg.cocos2dx.lib.Cocos2dxEditText;
- importorg.cocos2dx.lib.Cocos2dxGLSurfaceView;
- importorg.cocos2dx.lib.Cocos2dxRenderer;
- importandroid.app.ActivityManager;
- importandroid.content.Context;
- importandroid.content.Intent;
- importandroid.content.pm.ConfigurationInfo;
- importandroid.os.Bundle;
- importandroid.util.Log;
- importandroid.view.ViewGroup;
- importandroid.widget.FrameLayout;
- publicclassplayvideoextendsCocos2dxActivity{
- //当前类实例
- publicstaticplayvideoinstance;
- //用于切换Activity
- publicstaticIntentintent;
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- instance=this;
- if(detectOpenGLES20()){
- //getthepackageName,it'susedtosettheresourcepath
- StringpackageName=getApplication().getPackageName();
- super.setPackageName(packageName);
- //FrameLayout
- ViewGroup.LayoutParamsframelayout_params=
- newViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
- ViewGroup.LayoutParams.FILL_PARENT);
- FrameLayoutframelayout=newFrameLayout(this);
- framelayout.setLayoutParams(framelayout_params);
- //Cocos2dxEditTextlayout
- ViewGroup.LayoutParamsedittext_layout_params=
- newViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
- ViewGroup.LayoutParams.WRAP_CONTENT);
- Cocos2dxEditTextedittext=newCocos2dxEditText(this);
- edittext.setLayoutParams(edittext_layout_params);
- //...addtoFrameLayout
- framelayout.addView(edittext);
- //Cocos2dxGLSurfaceView
- mGLView=newCocos2dxGLSurfaceView(this);
- //...addtoFrameLayout
- framelayout.addView(mGLView);
- mGLView.setEGLContextClientVersion(2);
- mGLView.setCocos2dxRenderer(newCocos2dxRenderer());
- mGLView.setTextField(edittext);
- //Setframelayoutasthecontentview
- setContentView(framelayout);
- intent=newIntent(playvideo.this,VedioActivity.class);
- }
- else{
- Log.d("activity","don'tsupportgles2.0");
- finish();
- }
- }
- voidplayVideo()
- {
- instance.startActivity(intent);
- }
- @Override
- protectedvoidonPause(){
- super.onPause();
- mGLView.onPause();
- }
- @Override
- protectedvoidonResume(){
- super.onResume();
- mGLView.onResume();
- }
- privatebooleandetectOpenGLES20()
- {
- ActivityManageram=
- (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
- ConfigurationInfoinfo=am.getDeviceConfigurationInfo();
- return(info.reqGlEsVersion>=0x20000);
- }
- static{
- System.loadLibrary("game");
- }
- }
VideoView.java
- packageorg.cocos2dx.playvideo;
- importjava.io.IOException;
- importandroid.content.Context;
- importandroid.content.Intent;
- importandroid.media.AudioManager;
- importandroid.media.MediaPlayer;
- importandroid.media.MediaPlayer.OnCompletionListener;
- importandroid.media.MediaPlayer.OnErrorListener;
- importandroid.net.Uri;
- importandroid.util.AttributeSet;
- importandroid.view.KeyEvent;
- importandroid.view.MotionEvent;
- importandroid.view.SurfaceHolder;
- importandroid.view.SurfaceHolder.Callback;
- importandroid.view.SurfaceView;
- importandroid.view.View;
- importandroid.view.ViewGroup.LayoutParams;
- importandroid.widget.MediaController;
- importandroid.widget.MediaController.MediaPlayerControl;
- publicclassVideoViewextendsSurfaceViewimplementsMediaPlayerControl,Callback{
- privateContextmContext;
- //settablebytheclient
- privateUrimUri;
- privateintmDuration;
- //Allthestuffweneedforplayingandshowingavideo
- privateSurfaceHoldermSurfaceHolder=null;
- privateMediaPlayermMediaPlayer=null;
- privatebooleanmIsPrepared;
- privateintmVideoWidth;
- privateintmVideoHeight;
- privateintmSurfaceWidth;
- privateintmSurfaceHeight;
- privateMediaControllermMediaController;
- privateOnCompletionListenermOnCompletionListener;
- privateMediaPlayer.OnPreparedListenermOnPreparedListener;
- privateintmCurrentBufferPercentage;
- privateOnErrorListenermOnErrorListener;
- privatebooleanmStartWhenPrepared;
- privateintmSeekWhenPrepared;
- privateMySizeChangeLinstenermMyChangeLinstener;
- publicintgetVideoWidth(){
- returnmVideoWidth;
- }
- publicintgetVideoHeight(){
- returnmVideoHeight;
- }
- publicvoidsetVideoScale(intwidth,intheight){
- LayoutParamslp=getLayoutParams();
- lp.height=height;
- lp.width=width;
- setLayoutParams(lp);
- }
- publicinterfaceMySizeChangeLinstener{
- publicvoiddoMyThings();
- }
- publicvoidsetMySizeChangeLinstener(MySizeChangeLinstenerl){
- mMyChangeLinstener=l;
- }
- publicVideoView(Contextcontext){
- super(context);
- mContext=context;
- initVideoView();
- }
- publicVideoView(Contextcontext,AttributeSetattrs){
- this(context,attrs,0);
- mContext=context;
- initVideoView();
- }
- publicVideoView(Contextcontext,AttributeSetattrs,intdefStyle){
- super(context,attrs,defStyle);
- mContext=context;
- initVideoView();
- }
- @Override
- protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
- //Log.i("@@@@","onMeasure");
- intwidth=getDefaultSize(mVideoWidth,widthMeasureSpec);
- intheight=getDefaultSize(mVideoHeight,heightMeasureSpec);
- /*
- *if(mVideoWidth>0&&mVideoHeight>0){if(mVideoWidth*height
- *>width*mVideoHeight){//Log.i("@@@",
- *"imagetootall,correcting");height=width*mVideoHeight/
- *mVideoWidth;}elseif(mVideoWidth*height<width*mVideoHeight
- *){//Log.i("@@@","imagetoowide,correcting");width=height*
- *mVideoWidth/mVideoHeight;}else{//Log.i("@@@",
- *"aspectratioiscorrect:"+//width+"/"+height+"="+
- *//mVideoWidth+"/"+mVideoHeight);}}
- */
- //Log.i("@@@@@@@@@@","settingsize:"+width+'x'+height);
- setMeasuredDimension(width,height);
- }
- publicintresolveAdjustedSize(intdesiredSize,intmeasureSpec){
- intresult=desiredSize;
- intspecMode=MeasureSpec.getMode(measureSpec);
- intspecSize=MeasureSpec.getSize(measureSpec);
- switch(specMode){
- caseMeasureSpec.UNSPECIFIED:
- /*
- *Parentsayswecanbeasbigaswewant.Justdon'tbelarger
- *thanmaxsizeimposedonourselves.
- */
- result=desiredSize;
- break;
- caseMeasureSpec.AT_MOST:
- /*
- *Parentsayswecanbeasbigaswewant,uptospecSize.Don'tbe
- *largerthanspecSize,anddon'tbelargerthanthemaxsize
- *imposedonourselves.
- */
- result=Math.min(desiredSize,specSize);
- break;
- caseMeasureSpec.EXACTLY:
- //Nochoice.Dowhatwearetold.
- result=specSize;
- break;
- }
- returnresult;
- }
- privatevoidinitVideoView(){
- mVideoWidth=0;
- mVideoHeight=0;
- getHolder().addCallback(this);
- getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
- setFocusable(true);
- setFocusableInTouchMode(true);
- requestFocus();
- }
- publicvoidsetVideoPath(Stringpath){
- setVideoURI(Uri.parse(path));
- }
- publicvoidsetVideoURI(Uriuri){
- mUri=uri;
- mStartWhenPrepared=false;
- mSeekWhenPrepared=0;
- openVideo();
- requestLayout();
- invalidate();
- }
- publicvoidstopPlayback(){
- if(mMediaPlayer!=null){
- mMediaPlayer.stop();
- mMediaPlayer.release();
- mMediaPlayer=null;
- }
- }
- privatevoidopenVideo(){
- if(mUri==null||mSurfaceHolder==null){
- //notreadyforplaybackjustyet,willtryagainlater
- return;
- }
- //Tellthemusicplaybackservicetopause
- //TODO:theseconstantsneedtobepublishedsomewhereinthe
- //framework.
- Intenti=newIntent("com.android.music.musicservicecommand");
- i.putExtra("command","pause");
- mContext.sendBroadcast(i);
- if(mMediaPlayer!=null){
- mMediaPlayer.reset();
- mMediaPlayer.release();
- mMediaPlayer=null;
- }
- try{
- mMediaPlayer=newMediaPlayer();
- mMediaPlayer.setOnPreparedListener(mPreparedListener);
- mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
- mIsPrepared=false;
- //Log.v(TAG,"resetdurationto-1inopenVideo");
- mDuration=-1;
- mMediaPlayer.setOnCompletionListener(mCompletionListener);
- mMediaPlayer.setOnErrorListener(mErrorListener);
- mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
- mCurrentBufferPercentage=0;
- mMediaPlayer.setDataSource(mContext,mUri);
- mMediaPlayer.setDisplay(mSurfaceHolder);
- mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
- mMediaPlayer.setScreenOnWhilePlaying(true);
- mMediaPlayer.prepareAsync();
- attachMediaController();
- }catch(IOExceptionex){
- //Log.w(TAG,"Unabletoopencontent:"+mUri,ex);
- return;
- }catch(IllegalArgumentExceptionex){
- //Log.w(TAG,"Unabletoopencontent:"+mUri,ex);
- return;
- }
- }
- publicvoidsetMediaController(MediaControllercontroller){
- if(mMediaController!=null){
- mMediaController.hide();
- }
- mMediaController=controller;
- attachMediaController();
- }
- privatevoidattachMediaController(){
- if(mMediaPlayer!=null&&mMediaController!=null){
- mMediaController.setMediaPlayer(this);
- ViewanchorView=this.getParent()instanceofView?(View)this
- .getParent():this;
- mMediaController.setAnchorView(anchorView);
- mMediaController.setEnabled(mIsPrepared);
- }
- }
- MediaPlayer.OnVideoSizeChangedListenermSizeChangedListener=newMediaPlayer.OnVideoSizeChangedListener(){
- publicvoidonVideoSizeChanged(MediaPlayermp,intwidth,intheight){
- mVideoWidth=mp.getVideoWidth();
- mVideoHeight=mp.getVideoHeight();
- if(mMyChangeLinstener!=null){
- mMyChangeLinstener.doMyThings();
- }
- if(mVideoWidth!=0&&mVideoHeight!=0){
- getHolder().setFixedSize(mVideoWidth,mVideoHeight);
- }
- }
- };
- MediaPlayer.OnPreparedListenermPreparedListener=newMediaPlayer.OnPreparedListener(){
- publicvoidonPrepared(MediaPlayermp){
- //brieflyshowthemediacontroller
- mIsPrepared=true;
- if(mOnPreparedListener!=null){
- mOnPreparedListener.onPrepared(mMediaPlayer);
- }
- if(mMediaController!=null){
- mMediaController.setEnabled(true);
- }
- mVideoWidth=mp.getVideoWidth();
- mVideoHeight=mp.getVideoHeight();
- if(mVideoWidth!=0&&mVideoHeight!=0){
- //Log.i("@@@@","videosize:"+mVideoWidth+"/"+
- //mVideoHeight);
- getHolder().setFixedSize(mVideoWidth,mVideoHeight);
- if(mSurfaceWidth==mVideoWidth
- &&mSurfaceHeight==mVideoHeight){
- //Wedidn'tactuallychangethesize(itwasalreadyatthe
- //size
- //weneed),sowewon'tgeta"surfacechanged"callback,
- //so
- //startthevideohereinsteadofinthecallback.
- if(mSeekWhenPrepared!=0){
- mMediaPlayer.seekTo(mSeekWhenPrepared);
- mSeekWhenPrepared=0;
- }
- if(mStartWhenPrepared){
- mMediaPlayer.start();
- mStartWhenPrepared=false;
- if(mMediaController!=null){
- mMediaController.show();
- }
- }elseif(!isPlaying()
- &&(mSeekWhenPrepared!=0||getCurrentPosition()>0)){
- if(mMediaController!=null){
- //Showthemediacontrolswhenwe'repausedintoa
- //videoandmake'emstick.
- mMediaController.show(0);
- }
- }
- }
- }else{
- //Wedon'tknowthevideosizeyet,butshouldstartanyway.
- //Thevideosizemightbereportedtouslater.
- if(mSeekWhenPrepared!=0){
- mMediaPlayer.seekTo(mSeekWhenPrepared);
- mSeekWhenPrepared=0;
- }
- if(mStartWhenPrepared){
- mMediaPlayer.start();
- mStartWhenPrepared=false;
- }
- }
- }
- };
- privateMediaPlayer.OnCompletionListenermCompletionListener=newMediaPlayer.OnCompletionListener(){
- publicvoidonCompletion(MediaPlayermp){
- if(mMediaController!=null){
- mMediaController.hide();
- }
- if(mOnCompletionListener!=null){
- mOnCompletionListener.onCompletion(mMediaPlayer);
- }
- }
- };
- privateMediaPlayer.OnErrorListenermErrorListener=newMediaPlayer.OnErrorListener(){
- publicbooleanonError(MediaPlayermp,intframework_err,intimpl_err){
- //Log.d(TAG,"Error:"+framework_err+","+impl_err);
- if(mMediaController!=null){
- mMediaController.hide();
- }
- /*Ifanerrorhandlerhasbeensupplied,useitandfinish.*/
- if(mOnErrorListener!=null){
- if(mOnErrorListener.onError(mMediaPlayer,framework_err,
- impl_err)){
- returntrue;
- }
- }
- /*
- *Otherwise,popupanerrordialogsotheuserknowsthat
- *somethingbadhashappened.Onlytryandpopupthedialogif
- *we'reattachedtoawindow.Whenwe'regoingawayandnolonger
- *haveawindow,don'tbothershowingtheuseranerror.
- */
- if(getWindowToken()!=null){
- /*
- *if(framework_err==
- *MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK){
- *messageId=com.android.internal.R.string.
- *VideoView_error_text_invalid_progressive_playback;}else{
- *messageId=
- *com.android.internal.R.string.VideoView_error_text_unknown;}
- *
- *newAlertDialog.Builder(mContext)
- *.setTitle(com.android.internal
- *.R.string.VideoView_error_title).setMessage(messageId)
- *.setPositiveButton
- *(com.android.internal.R.string.VideoView_error_button,new
- *DialogInterface.OnClickListener(){publicvoid
- *onClick(DialogInterfacedialog,intwhichButton){Ifweget
- *here,thereisnoonErrorlistener,soatleastinformthem
- *thatthevideoisover.
- *
- *if(mOnCompletionListener!=null){
- *mOnCompletionListener.onCompletion(mMediaPlayer);}}})
- *.setCancelable(false).show();
- */
- }
- returntrue;
- }
- };
- privateMediaPlayer.OnBufferingUpdateListenermBufferingUpdateListener=newMediaPlayer.OnBufferingUpdateListener(){
- publicvoidonBufferingUpdate(MediaPlayermp,intpercent){
- mCurrentBufferPercentage=percent;
- }
- };
- /**
- *Registeracallbacktobeinvokedwhenthemediafileisloadedandready
- *togo.
- *
- *@paraml
- *Thecallbackthatwillberun
- */
- publicvoidsetOnPreparedListener(MediaPlayer.OnPreparedListenerl){
- mOnPreparedListener=l;
- }
- /**
- *Registeracallbacktobeinvokedwhentheendofamediafilehasbeen
- *reachedduringplayback.
- *
- *@paraml
- *Thecallbackthatwillberun
- */
- publicvoidsetOnCompletionListener(OnCompletionListenerl){
- mOnCompletionListener=l;
- }
- /**
- *Registeracallbacktobeinvokedwhenanerroroccursduringplaybackor
- *setup.Ifnolistenerisspecified,orifthelistenerreturnedfalse,
- *VideoViewwillinformtheuserofanyerrors.
- *
- *@paraml
- *Thecallbackthatwillberun
- */
- publicvoidsetOnErrorListener(OnErrorListenerl){
- mOnErrorListener=l;
- }
- @Override
- publicbooleanonTouchEvent(MotionEventev){
- if(mIsPrepared&&mMediaPlayer!=null&&mMediaController!=null){
- toggleMediaControlsVisiblity();
- }
- returnfalse;
- }
- @Override
- publicbooleanonTrackballEvent(MotionEventev){
- if(mIsPrepared&&mMediaPlayer!=null&&mMediaController!=null){
- toggleMediaControlsVisiblity();
- }
- returnfalse;
- }
- @Override
- publicbooleanonKeyDown(intkeyCode,KeyEventevent){
- if(mIsPrepared&&keyCode!=KeyEvent.KEYCODE_BACK
- &&keyCode!=KeyEvent.KEYCODE_VOLUME_UP
- &&keyCode!=KeyEvent.KEYCODE_VOLUME_DOWN
- &&keyCode!=KeyEvent.KEYCODE_MENU
- &&keyCode!=KeyEvent.KEYCODE_CALL
- &&keyCode!=KeyEvent.KEYCODE_ENDCALL&&mMediaPlayer!=null
- &&mMediaController!=null){
- if(keyCode==KeyEvent.KEYCODE_HEADSETHOOK
- ||keyCode==KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE){
- if(mMediaPlayer.isPlaying()){
- pause();
- mMediaController.show();
- }else{
- start();
- mMediaController.hide();
- }
- returntrue;
- }elseif(keyCode==KeyEvent.KEYCODE_MEDIA_STOP
- &&mMediaPlayer.isPlaying()){
- pause();
- mMediaController.show();
- }else{
- toggleMediaControlsVisiblity();
- }
- }
- returnsuper.onKeyDown(keyCode,event);
- }
- privatevoidtoggleMediaControlsVisiblity(){
- if(mMediaController.isShowing()){
- mMediaController.hide();
- }else{
- mMediaController.show();
- }
- }
- publicvoidstart(){
- if(mMediaPlayer!=null&&mIsPrepared){
- mMediaPlayer.start();
- mStartWhenPrepared=false;
- }else{
- mStartWhenPrepared=true;
- }
- }
- publicvoidpause(){
- if(mMediaPlayer!=null&&mIsPrepared){
- if(mMediaPlayer.isPlaying()){
- mMediaPlayer.pause();
- }
- }
- mStartWhenPrepared=false;
- }
- publicintgetDuration(){
- if(mMediaPlayer!=null&&mIsPrepared){
- if(mDuration>0){
- returnmDuration;
- }
- mDuration=mMediaPlayer.getDuration();
- returnmDuration;
- }
- mDuration=-1;
- returnmDuration;
- }
- publicintgetCurrentPosition(){
- if(mMediaPlayer!=null&&mIsPrepared){
- returnmMediaPlayer.getCurrentPosition();
- }
- return0;
- }
- publicvoidseekTo(intmsec){
- if(mMediaPlayer!=null&&mIsPrepared){
- mMediaPlayer.seekTo(msec);
- }else{
- mSeekWhenPrepared=msec;
- }
- }
- publicbooleanisPlaying(){
- if(mMediaPlayer!=null&&mIsPrepared){
- returnmMediaPlayer.isPlaying();
- }
- returnfalse;
- }
- publicintgetBufferPercentage(){
- if(mMediaPlayer!=null){
- returnmCurrentBufferPercentage;
- }
- return0;
- }
- publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,
- intheight){
- mSurfaceWidth=width;
- mSurfaceHeight=height;
- if(mMediaPlayer!=null&&mIsPrepared&&mVideoWidth==width
- &&mVideoHeight==height){
- if(mSeekWhenPrepared!=0){
- mMediaPlayer.seekTo(mSeekWhenPrepared);
- mSeekWhenPrepared=0;
- }
- mMediaPlayer.start();
- if(mMediaController!=null){
- mMediaController.show();
- }
- }
- }
- publicvoidsurfaceCreated(SurfaceHolderholder){
- mSurfaceHolder=holder;
- openVideo();
- }
- publicvoidsurfaceDestroyed(SurfaceHolderholder){
- //afterwereturnfromthiswecan'tusethesurfaceanymore
- mSurfaceHolder=null;
- if(mMediaController!=null)
- mMediaController.hide();
- if(mMediaPlayer!=null){
- mMediaPlayer.reset();
- mMediaPlayer.release();
- mMediaPlayer=null;
- }
- }
- publicbooleancanPause(){
- //TODOAuto-generatedmethodstub
- returnfalse;
- }
- publicbooleancanSeekBackward(){
- //TODOAuto-generatedmethodstub
- returnfalse;
- }
- publicbooleancanSeekForward(){
- //TODOAuto-generatedmethodstub
- returnfalse;
- }
- }
- packageorg.cocos2dx.playvideo;
- importandroid.app.Activity;
- importandroid.media.MediaPlayer;
- importandroid.net.Uri;
- importandroid.os.Bundle;
- importandroid.view.Window;
- importandroid.view.WindowManager;
- publicclassVedioActivityextendsActivityimplementsMediaPlayer.OnCompletionListener{
- @Override
- protectedvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- //隐藏标题栏
- this.requestWindowFeature(Window.FEATURE_NO_TITLE);
- //隐藏状态栏
- this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
- //初始化视频View
- VideoViewview=newVideoView(this);
- //设置显示视频View
- setContentView(view);
- //注册监听视频
- view.setOnCompletionListener(this);
- //设置视频文件路径
- view.setVideoURI(Uri.parse("android.resource://org.cocos2dx.playvideo/"+R.raw.xcm));
- //播放视频
- view.start();
- }
- //当视频播放完后回调此函数
- @Override
- publicvoidonCompletion(MediaPlayermp){
- //结束当前Activity
- this.finish();
- }
- }
二.播放网络视频
IOS项目:
在RootViewController.h里添加playURLVideo函数
并导入头文件#import"MediaPlayer/MediaPlayer.h"
RootViewController.mm实现playURLVideo函数如下:
- -(void)playURLVideo
- {
- NSURL*movieUrl=[NSURLURLWithString:@"http://v.youku.com/player/getRealM3U8/vid/XMzU5NDE3NTYw/type//video.m3u8"];
- MPMoviePlayerViewController*player=[[MPMoviePlayerViewControlleralloc]initWithContentURL:movieUrl];
- [selfpresentMoviePlayerViewControllerAnimated:player];
- }
然后修改AppController.mm里的函数
- -(void)playVideo
- {
- //CCSizesize=CCDirector::sharedDirector()->getWinSize();
- //[CCVideoPlayersetScrrenSize:CGSizeMake(size.width-400,size.height-300)];
- //[CCVideoPlayersetNoSkip:true];
- //[CCVideoPlayerplayMovieWithFile:@"xcm.mp4"];
- //播放网络视频
- [viewControllerplayURLVideo];
- }
Android项目:修改playvideo.java
修改后如下:
- packageorg.cocos2dx.playvideo;
- importorg.cocos2dx.lib.Cocos2dxActivity;
- importandroid.net.Uri;
- importandroid.os.Bundle;
- importandroid.content.Intent;
- publicclassplayvideoextendsCocos2dxActivity{
- //当前类实例
- publicstaticplayvideoinstance;
- //用于切换Activity
- publicstaticIntentintent;
- publicvoidonCreate(BundlesavedInstanceState){
- super.onCreate(savedInstanceState);
- instance=this;
- }
- voidplayURLVideo()
- {
- Intentintent=newIntent(Intent.ACTION_VIEW);
- Stringtype="video/*";
- Uriuri=Uri.parse("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
- intent.setDataAndType(uri,type);
- instance.startActivity(intent);
- }
- static{
- System.loadLibrary("game");
- }
- }