cocos2d-x IOS 和Android播放视频(包括网络视频)

前端之家收集整理的这篇文章主要介绍了cocos2d-x IOS 和Android播放视频(包括网络视频)前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
一.播放本地视频

对于iOS平台的视频播放,我们可以借助Cocos2d-iphone 的Extensions:CCVideoPlayer来实现

1.导入支持cocos2d-x的扩展库到项目中(这里可以参考Himi的第六章视频播放小节内容,这里的扩展库是Himi修改好的,我就直接拿来用了!希望没有侵权!)

2.添加MediaPalyer框架到项目中

3.修改ios里AppController.h 和AppController.mm文件

AppController.h

[plain] view plain copy
  1. #import"../Classes/CCVideoPlayeriOS/CCVideoPlayer.h"
  2. @classRootViewController;
  3. @interfaceAppController:NSObject<UIAccelerometerDelegate,UIAlertViewDelegate,
  4. UITextFieldDelegate,UIApplicationDelegate,CCVideoPlayerDelegate>
  5. {
  6. UIWindow*window;
  7. RootViewController*viewController;
  8. }
  9. @property(nonatomic,retain)UIWindow*window;
  10. @property(nonatomic,retain)RootViewController*viewController;
  11. -(void)playVideo;
  12. @end

AppController.mm

添加using namespace cocos2d;

因为playVideo用到了cocos2d-x里的api

CCSizesize = CCDirector::sharedDirector()->getWinSize();

在application函数添加视频播放监听

[CCVideoPlayer setDelegate :self];

playVideo实现如下:

copy
    -(void)playVideo
  1. {
  2. CCSizesize=CCDirector::sharedDirector()->getWinSize();
  3. [CCVideoPlayersetScrrenSize:CGSizeMake(size.width-400,size.height-300)];
  4. [CCVideoPlayersetNoSkip:true];
  5. [CCVideoPlayerplayMovieWithFile:@"xcm.mp4"];
  6. //播放网络视频
  7. //[viewControllerplayURLVideo];
  8. }

4.添加混编类IOSPlayVideo

IOSPlayVideo.h

copy
    #ifndef__IOSPlayVideo_SCENE_H__
  1. #define__IOSPlayVideo_SCENE_H__
  2. classIOSPlayVideo
  3. public:
  4. staticvoidplayVideoForIOS();
  5. };
  6. #endif//__IOSPlayVideo_SCENE_H__

IOSPlayVideo.mm

copy
    #include"IOSPlayVideo.h"
  1. #include"AppController.h"
  2. voidioSPlayVideo::playVideoForIOS()
  3. AppController*app=(AppController*)[[UIApplicationsharedApplication]delegate];
  4. [appplayVideo];
  5. }

5.添加一个cocos2d-x类 :Platform

Platform.h

copy
    #ifndef__Platform_SCENE_H__
  1. #define__Platform_SCENE_H__
  2. #include"cocos2d.h"
  3. usingnamespacecocos2d;
  4. classPlatform
  5. public:
  6. staticvoidplayVideo();//用于播放本地视频
  7. staticvoidplayURLVideo();//用于播放网络视频
  8. };
  9. #endif//__Platform_SCENE_H__


Platform.mm

copy
    #include"Platform.h"
  1. #include"../cocos2dx/platform/CCPlatformConfig.h"
  2. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  3. #include<jni.h>
  4. #include"../cocos2dx/platform/android/jni/JniHelper.h"
  5. #include<android/log.h>
  6. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  7. #include"IOSPlayVideo.h"
  8. #endif
  9. voidPlatform::playVideo()
  10. //Android播放本地视频
  11. JniMethodInfominfo;
  12. boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/playvideo/playvideo","playVedio","()V");
  13. if(isHave)
  14. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
  15. //IOS播放本地视频
  16. IOSPlayVideo::playVideoForIOS();
  17. #endif
  18. }
  19. voidPlatform::playURLVideo()
  20. //Android播放网络视频
  21. //IOS播放网络视频
  22. }

IOS项目里只需在需要的地方调用函数就可以播放视频了!

至于Android就稍微麻烦一点,需要用到Jni 技术,C++调用Java

A.修改playvideo.java

修改后如下:

@H_489_404@ [java] copy
    packageorg.cocos2dx.playvideo;
  1. importorg.cocos2dx.lib.Cocos2dxActivity;
  2. importorg.cocos2dx.lib.Cocos2dxEditText;
  3. importorg.cocos2dx.lib.Cocos2dxGLSurfaceView;
  4. importorg.cocos2dx.lib.Cocos2dxRenderer;
  5. importandroid.app.ActivityManager;
  6. importandroid.content.Context;
  7. importandroid.content.Intent;
  8. importandroid.content.pm.ConfigurationInfo;
  9. importandroid.os.Bundle;
  10. importandroid.util.Log;
  11. importandroid.view.ViewGroup;
  12. importandroid.widget.FrameLayout;
  13. publicclassplayvideoextendsCocos2dxActivity{
  14. //当前类实例
  15. publicstaticplayvideoinstance;
  16. //用于切换Activity
  17. publicstaticIntentintent;
  18. protectedvoidonCreate(BundlesavedInstanceState){
  19. super.onCreate(savedInstanceState);
  20. instance=this;
  21. if(detectOpenGLES20()){
  22. //getthepackageName,it'susedtosettheresourcepath
  23. StringpackageName=getApplication().getPackageName();
  24. super.setPackageName(packageName);
  25. //FrameLayout
  26. ViewGroup.LayoutParamsframelayout_params=
  27. newViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
  28. ViewGroup.LayoutParams.FILL_PARENT);
  29. FrameLayoutframelayout=newFrameLayout(this);
  30. framelayout.setLayoutParams(framelayout_params);
  31. //Cocos2dxEditTextlayout
  32. ViewGroup.LayoutParamsedittext_layout_params=
  33. newViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
  34. ViewGroup.LayoutParams.WRAP_CONTENT);
  35. Cocos2dxEditTextedittext=newCocos2dxEditText(this);
  36. edittext.setLayoutParams(edittext_layout_params);
  37. //...addtoFrameLayout
  38. framelayout.addView(edittext);
  39. //Cocos2dxGLSurfaceView
  40. mGLView=newCocos2dxGLSurfaceView(this);
  41. framelayout.addView(mGLView);
  42. mGLView.setEGLContextClientVersion(2);
  43. mGLView.setCocos2dxRenderer(newCocos2dxRenderer());
  44. mGLView.setTextField(edittext);
  45. //Setframelayoutasthecontentview
  46. setContentView(framelayout);
  47. intent=newIntent(playvideo.this,VedioActivity.class);
  48. else{
  49. Log.d("activity","don'tsupportgles2.0");
  50. finish();
  51. voidplayVideo()
  52. instance.startActivity(intent);
  53. @Override
  54. protectedvoidonPause(){
  55. super.onPause();
  56. mGLView.onPause();
  57. protectedvoidonResume(){
  58. super.onResume();
  59. mGLView.onResume();
  60. privatebooleandetectOpenGLES20()
  61. ActivityManageram=
  62. (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE);
  63. ConfigurationInfoinfo=am.getDeviceConfigurationInfo();
  64. return(info.reqGlEsVersion>=0x20000);
  65. static{
  66. System.loadLibrary("game");
  67. }
添加两个.java文件:VideoView.java和VedioActivity.java

VideoView.java

copy
    importjava.io.IOException;
  1. importandroid.media.AudioManager;
  2. importandroid.media.MediaPlayer;
  3. importandroid.media.MediaPlayer.OnCompletionListener;
  4. importandroid.media.MediaPlayer.OnErrorListener;
  5. importandroid.net.Uri;
  6. importandroid.util.AttributeSet;
  7. importandroid.view.KeyEvent;
  8. importandroid.view.MotionEvent;
  9. importandroid.view.SurfaceHolder;
  10. importandroid.view.SurfaceHolder.Callback;
  11. importandroid.view.SurfaceView;
  12. importandroid.view.View;
  13. importandroid.view.ViewGroup.LayoutParams;
  14. importandroid.widget.MediaController;
  15. importandroid.widget.MediaController.MediaPlayerControl;
  16. publicclassVideoViewextendsSurfaceViewimplementsMediaPlayerControl,Callback{
  17. privateContextmContext;
  18. //settablebytheclient
  19. privateUrimUri;
  20. privateintmDuration;
  21. //Allthestuffweneedforplayingandshowingavideo
  22. privateSurfaceHoldermSurfaceHolder=null;
  23. privateMediaPlayermMediaPlayer=null;
  24. privatebooleanmIsPrepared;
  25. privateintmVideoWidth;
  26. privateintmVideoHeight;
  27. privateintmSurfaceWidth;
  28. privateintmSurfaceHeight;
  29. privateMediaControllermMediaController;
  30. privateOnCompletionListenermOnCompletionListener;
  31. privateMediaPlayer.OnPreparedListenermOnPreparedListener;
  32. privateintmCurrentBufferPercentage;
  33. privateOnErrorListenermOnErrorListener;
  34. privatebooleanmStartWhenPrepared;
  35. privateintmSeekWhenPrepared;
  36. privateMySizeChangeLinstenermMyChangeLinstener;
  37. publicintgetVideoWidth(){
  38. returnmVideoWidth;
  39. publicintgetVideoHeight(){
  40. returnmVideoHeight;
  41. publicvoidsetVideoScale(intwidth,intheight){
  42. LayoutParamslp=getLayoutParams();
  43. lp.height=height;
  44. lp.width=width;
  45. setLayoutParams(lp);
  46. publicinterfaceMySizeChangeLinstener{
  47. publicvoiddoMyThings();
  48. publicvoidsetMySizeChangeLinstener(MySizeChangeLinstenerl){
  49. mMyChangeLinstener=l;
  50. publicVideoView(Contextcontext){
  51. super(context);
  52. mContext=context;
  53. initVideoView();
  54. publicVideoView(Contextcontext,AttributeSetattrs){
  55. this(context,attrs,0);
  56. intdefStyle){
  57. super(context,defStyle);
  58. @Override
  59. protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
  60. //Log.i("@@@@","onMeasure");
  61. intwidth=getDefaultSize(mVideoWidth,widthMeasureSpec);
  62. intheight=getDefaultSize(mVideoHeight,heightMeasureSpec);
  63. /*
  64. *if(mVideoWidth>0&&mVideoHeight>0){if(mVideoWidth*height
  65. *>width*mVideoHeight){//Log.i("@@@",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> *"imagetootall,correcting");height=width*mVideoHeight/
  66. *mVideoWidth;}elseif(mVideoWidth*height<width*mVideoHeight
  67. *){//Log.i("@@@","imagetoowide,correcting");width=height*
  68. *mVideoWidth/mVideoHeight;}else{//Log.i("@@@",108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> *"aspectratioiscorrect:"+//width+"/"+height+"="+
  69. *//mVideoWidth+"/"+mVideoHeight);}}
  70. */
  71. //Log.i("@@@@@@@@@@","settingsize:"+width+'x'+height);
  72. setMeasuredDimension(width,height);
  73. publicintresolveAdjustedSize(intdesiredSize,intmeasureSpec){
  74. intresult=desiredSize;
  75. intspecMode=MeasureSpec.getMode(measureSpec);
  76. intspecSize=MeasureSpec.getSize(measureSpec);
  77. switch(specMode){
  78. caseMeasureSpec.UNSPECIFIED:
  79. /*
  80. *Parentsayswecanbeasbigaswewant.Justdon'tbelarger
  81. *thanmaxsizeimposedonourselves.
  82. */
  83. result=desiredSize;
  84. break;
  85. caseMeasureSpec.AT_MOST:
  86. *Parentsayswecanbeasbigaswewant,uptospecSize.Don'tbe
  87. *largerthanspecSize,anddon'tbelargerthanthemaxsize
  88. *imposedonourselves.
  89. result=Math.min(desiredSize,specSize);
  90. break;
  91. caseMeasureSpec.EXACTLY:
  92. //Nochoice.Dowhatwearetold.
  93. result=specSize;
  94. returnresult;
  95. privatevoidinitVideoView(){
  96. mVideoWidth=0;
  97. mVideoHeight=0;
  98. getHolder().addCallback(this);
  99. getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  100. setFocusable(true);
  101. setFocusableInTouchMode(true);
  102. requestFocus();
  103. publicvoidsetVideoPath(Stringpath){
  104. setVideoURI(Uri.parse(path));
  105. publicvoidsetVideoURI(Uriuri){
  106. mUri=uri;
  107. mStartWhenPrepared=false;
  108. mSeekWhenPrepared=0;
  109. openVideo();
  110. requestLayout();
  111. invalidate();
  112. publicvoidstopPlayback(){
  113. if(mMediaPlayer!=null){
  114. mMediaPlayer.stop();
  115. mMediaPlayer.release();
  116. mMediaPlayer=null;
  117. privatevoidopenVideo(){
  118. if(mUri==null||mSurfaceHolder==null){
  119. //notreadyforplaybackjustyet,willtryagainlater
  120. return;
  121. //Tellthemusicplaybackservicetopause
  122. //TODO:theseconstantsneedtobepublishedsomewhereinthe
  123. //framework.
  124. Intenti=newIntent("com.android.music.musicservicecommand");
  125. i.putExtra("command","pause");
  126. mContext.sendBroadcast(i);
  127. if(mMediaPlayer!=null){
  128. mMediaPlayer.reset();
  129. mMediaPlayer.release();
  130. mMediaPlayer=null;
  131. try{
  132. mMediaPlayer=newMediaPlayer();
  133. mMediaPlayer.setOnPreparedListener(mPreparedListener);
  134. mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
  135. mIsPrepared=false;
  136. //Log.v(TAG,"resetdurationto-1inopenVideo");
  137. mDuration=-1;
  138. mMediaPlayer.setOnCompletionListener(mCompletionListener);
  139. mMediaPlayer.setOnErrorListener(mErrorListener);
  140. mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
  141. mCurrentBufferPercentage=0;
  142. mMediaPlayer.setDataSource(mContext,mUri);
  143. mMediaPlayer.setDisplay(mSurfaceHolder);
  144. mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  145. mMediaPlayer.setScreenOnWhilePlaying(true);
  146. mMediaPlayer.prepareAsync();
  147. attachMediaController();
  148. }catch(IOExceptionex){
  149. //Log.w(TAG,"Unabletoopencontent:"+mUri,ex);
  150. return;
  151. }catch(IllegalArgumentExceptionex){
  152. //Log.w(TAG,ex);
  153. publicvoidsetMediaController(MediaControllercontroller){
  154. if(mMediaController!=null){
  155. mMediaController.hide();
  156. mMediaController=controller;
  157. attachMediaController();
  158. privatevoidattachMediaController(){
  159. if(mMediaPlayer!=null&&mMediaController!=null){
  160. mMediaController.setMediaPlayer(this);
  161. ViewanchorView=this.getParent()instanceofView?(View)this
  162. .getParent():this;
  163. mMediaController.setAnchorView(anchorView);
  164. mMediaController.setEnabled(mIsPrepared);
  165. MediaPlayer.OnVideoSizeChangedListenermSizeChangedListener=newMediaPlayer.OnVideoSizeChangedListener(){
  166. publicvoidonVideoSizeChanged(MediaPlayermp,intwidth,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> mVideoWidth=mp.getVideoWidth();
  167. mVideoHeight=mp.getVideoHeight();
  168. if(mMyChangeLinstener!=null){
  169. mMyChangeLinstener.doMyThings();
  170. if(mVideoWidth!=0&&mVideoHeight!=0){
  171. getHolder().setFixedSize(mVideoWidth,mVideoHeight);
  172. MediaPlayer.OnPreparedListenermPreparedListener=newMediaPlayer.OnPreparedListener(){
  173. publicvoidonPrepared(MediaPlayermp){
  174. //brieflyshowthemediacontroller
  175. mIsPrepared=true;
  176. if(mOnPreparedListener!=null){
  177. mOnPreparedListener.onPrepared(mMediaPlayer);
  178. if(mMediaController!=null){
  179. mMediaController.setEnabled(true);
  180. mVideoWidth=mp.getVideoWidth();
  181. mVideoHeight=mp.getVideoHeight();
  182. //mVideoHeight);
  183. if(mSurfaceWidth==mVideoWidth
  184. &&mSurfaceHeight==mVideoHeight){
  185. //Wedidn'tactuallychangethesize(itwasalreadyatthe
  186. //size
  187. //weneed),sowewon'tgeta"surfacechanged"callback,
  188. //so
  189. //startthevideohereinsteadofinthecallback.
  190. if(mSeekWhenPrepared!=0){
  191. mMediaPlayer.seekTo(mSeekWhenPrepared);
  192. mSeekWhenPrepared=0;
  193. if(mStartWhenPrepared){
  194. mMediaPlayer.start();
  195. mMediaController.show();
  196. }elseif(!isPlaying()
  197. &&(mSeekWhenPrepared!=0||getCurrentPosition()>0)){
  198. //Showthemediacontrolswhenwe'repausedintoa
  199. //videoandmake'emstick.
  200. mMediaController.show(0);
  201. }else{
  202. //Wedon'tknowthevideosizeyet,butshouldstartanyway.
  203. //Thevideosizemightbereportedtouslater.
  204. privateMediaPlayer.OnCompletionListenermCompletionListener=newMediaPlayer.OnCompletionListener(){
  205. publicvoidonCompletion(MediaPlayermp){
  206. mMediaController.hide();
  207. if(mOnCompletionListener!=null){
  208. mOnCompletionListener.onCompletion(mMediaPlayer);
  209. privateMediaPlayer.OnErrorListenermErrorListener=newMediaPlayer.OnErrorListener(){
  210. publicbooleanonError(MediaPlayermp,intframework_err,intimpl_err){
  211. //Log.d(TAG,"Error:"+framework_err+","+impl_err);
  212. /*Ifanerrorhandlerhasbeensupplied,useitandfinish.*/
  213. if(mOnErrorListener!=null){
  214. if(mOnErrorListener.onError(mMediaPlayer,framework_err,248); line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> impl_err)){
  215. returntrue;
  216. *Otherwise,popupanerrordialogsotheuserknowsthat
  217. *somethingbadhashappened.Onlytryandpopupthedialogif
  218. *we'reattachedtoawindow.Whenwe'regoingawayandnolonger
  219. *haveawindow,don'tbothershowingtheuseranerror.
  220. if(getWindowToken()!=null){
  221. *if(framework_err==
  222. *MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK){
  223. *messageId=com.android.internal.R.string.
  224. *VideoView_error_text_invalid_progressive_playback;}else{
  225. *messageId=
  226. *com.android.internal.R.string.VideoView_error_text_unknown;}
  227. *
  228. *newAlertDialog.Builder(mContext)
  229. *.setTitle(com.android.internal
  230. *.R.string.VideoView_error_title).setMessage(messageId)
  231. *.setPositiveButton
  232. *(com.android.internal.R.string.VideoView_error_button,new
  233. *DialogInterface.OnClickListener(){publicvoid
  234. *onClick(DialogInterfacedialog,intwhichButton){Ifweget
  235. *here,thereisnoonErrorlistener,soatleastinformthem
  236. *thatthevideoisover.
  237. *if(mOnCompletionListener!=null){
  238. *mOnCompletionListener.onCompletion(mMediaPlayer);}}})
  239. *.setCancelable(false).show();
  240. returntrue;
  241. privateMediaPlayer.OnBufferingUpdateListenermBufferingUpdateListener=newMediaPlayer.OnBufferingUpdateListener(){
  242. publicvoidonBufferingUpdate(MediaPlayermp,intpercent){
  243. mCurrentBufferPercentage=percent;
  244. /**
  245. *Registeracallbacktobeinvokedwhenthemediafileisloadedandready
  246. *togo.
  247. *
  248. *@paraml
  249. *Thecallbackthatwillberun
  250. publicvoidsetOnPreparedListener(MediaPlayer.OnPreparedListenerl){
  251. mOnPreparedListener=l;
  252. /**
  253. *Registeracallbacktobeinvokedwhentheendofamediafilehasbeen
  254. *reachedduringplayback.
  255. *@paraml
  256. *Thecallbackthatwillberun
  257. publicvoidsetOnCompletionListener(OnCompletionListenerl){
  258. mOnCompletionListener=l;
  259. *Registeracallbacktobeinvokedwhenanerroroccursduringplaybackor
  260. *setup.Ifnolistenerisspecified,orifthelistenerreturnedfalse,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> *VideoViewwillinformtheuserofanyerrors.
  261. publicvoidsetOnErrorListener(OnErrorListenerl){
  262. mOnErrorListener=l;
  263. publicbooleanonTouchEvent(MotionEventev){
  264. if(mIsPrepared&&mMediaPlayer!=null&&mMediaController!=null){
  265. toggleMediaControlsVisiblity();
  266. returnfalse;
  267. publicbooleanonTrackballEvent(MotionEventev){
  268. publicbooleanonKeyDown(intkeyCode,KeyEventevent){
  269. if(mIsPrepared&&keyCode!=KeyEvent.KEYCODE_BACK
  270. &&keyCode!=KeyEvent.KEYCODE_VOLUME_UP
  271. &&keyCode!=KeyEvent.KEYCODE_VOLUME_DOWN
  272. &&keyCode!=KeyEvent.KEYCODE_MENU
  273. &&keyCode!=KeyEvent.KEYCODE_CALL
  274. &&keyCode!=KeyEvent.KEYCODE_ENDCALL&&mMediaPlayer!=null
  275. &&mMediaController!=null){
  276. if(keyCode==KeyEvent.KEYCODE_HEADSETHOOK
  277. ||keyCode==KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE){
  278. if(mMediaPlayer.isPlaying()){
  279. pause();
  280. start();
  281. }elseif(keyCode==KeyEvent.KEYCODE_MEDIA_STOP
  282. &&mMediaPlayer.isPlaying()){
  283. pause();
  284. mMediaController.show();
  285. }else{
  286. toggleMediaControlsVisiblity();
  287. returnsuper.onKeyDown(keyCode,event);
  288. privatevoidtoggleMediaControlsVisiblity(){
  289. if(mMediaController.isShowing()){
  290. publicvoidstart(){
  291. if(mMediaPlayer!=null&&mIsPrepared){
  292. mMediaPlayer.start();
  293. mStartWhenPrepared=false;
  294. mStartWhenPrepared=true;
  295. publicvoidpause(){
  296. if(mMediaPlayer!=null&&mIsPrepared){
  297. if(mMediaPlayer.isPlaying()){
  298. mMediaPlayer.pause();
  299. publicintgetDuration(){
  300. if(mDuration>0){
  301. returnmDuration;
  302. mDuration=mMediaPlayer.getDuration();
  303. returnmDuration;
  304. publicintgetCurrentPosition(){
  305. returnmMediaPlayer.getCurrentPosition();
  306. return0;
  307. publicvoidseekTo(intmsec){
  308. mMediaPlayer.seekTo(msec);
  309. mSeekWhenPrepared=msec;
  310. publicbooleanisPlaying(){
  311. returnmMediaPlayer.isPlaying();
  312. returnfalse;
  313. publicintgetBufferPercentage(){
  314. returnmCurrentBufferPercentage;
  315. publicvoidsurfaceChanged(SurfaceHolderholder,intformat,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> intheight){
  316. mSurfaceWidth=width;
  317. mSurfaceHeight=height;
  318. if(mMediaPlayer!=null&&mIsPrepared&&mVideoWidth==width
  319. &&mVideoHeight==height){
  320. if(mSeekWhenPrepared!=0){
  321. mMediaPlayer.seekTo(mSeekWhenPrepared);
  322. publicvoidsurfaceCreated(SurfaceHolderholder){
  323. mSurfaceHolder=holder;
  324. publicvoidsurfaceDestroyed(SurfaceHolderholder){
  325. //afterwereturnfromthiswecan'tusethesurfaceanymore
  326. mSurfaceHolder=null;
  327. if(mMediaController!=null)
  328. mMediaPlayer.reset();
  329. publicbooleancanPause(){
  330. //TODOAuto-generatedmethodstub
  331. publicbooleancanSeekBackward(){
  332. //TODOAuto-generatedmethodstub
  333. publicbooleancanSeekForward(){
  334. }
VedioActivity.java

copy
    importandroid.app.Activity;
  1. importandroid.view.Window;
  2. importandroid.view.WindowManager;
  3. publicclassVedioActivityextendsActivityimplementsMediaPlayer.OnCompletionListener{
  4. //隐藏标题
  5. this.requestWindowFeature(Window.FEATURE_NO_TITLE);
  6. //隐藏状态栏
  7. this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
  8. //初始化视频View
  9. VideoViewview=newVideoView(this);
  10. //设置显示视频View
  11. setContentView(view);
  12. //注册监听视频
  13. view.setOnCompletionListener(this);
  14. //设置视频文件路径
  15. view.setVideoURI(Uri.parse("android.resource://org.cocos2dx.playvideo/"+R.raw.xcm));
  16. //播放视频
  17. view.start();
  18. //当视频播放完后回调此函数
  19. //结束当前Activity
  20. this.finish();
  21. }
注:在 res下新建一个名为raw的文件夹,将assets下xcm.mp4拷贝到raw文件夹下,否则 :raw 和xcm无法识别!!!

二.播放网络视频

IOS项目:

在RootViewController.h里添加playURLVideo函数

并导入头文件#import"MediaPlayer/MediaPlayer.h"

RootViewController.mm实现playURLVideo函数如下:

copy
    -(void)playURLVideo
  1. NSURL*movieUrl=[NSURLURLWithString:@"http://v.youku.com/player/getRealM3U8/vid/XMzU5NDE3NTYw/type//video.m3u8"];
  2. MPMoviePlayerViewController*player=[[MPMoviePlayerViewControlleralloc]initWithContentURL:movieUrl];
  3. [selfpresentMoviePlayerViewControllerAnimated:player];
  4. }

然后修改AppController.mm里的函数

copy
    //CCSizesize=CCDirector::sharedDirector()->getWinSize();
  1. //[CCVideoPlayersetScrrenSize:CGSizeMake(size.width-400,108); list-style:decimal-leading-zero outside; color:inherit; line-height:18px; margin:0px!important; padding:0px 3px 0px 10px!important"> //[CCVideoPlayersetNoSkip:true];
  2. //[CCVideoPlayerplayMovieWithFile:@"xcm.mp4"];
  3. [viewControllerplayURLVideo];
  4. }

Android项目:修改playvideo.java

修改后如下:

copy
    importandroid.content.Intent;
  1. publicclassplayvideoextendsCocos2dxActivity{
  2. //当前类实例
  3. publicstaticplayvideoinstance;
  4. //用于切换Activity
  5. publicstaticIntentintent;
  6. publicvoidonCreate(BundlesavedInstanceState){
  7. super.onCreate(savedInstanceState);
  8. voidplayURLVideo()
  9. Intentintent=newIntent(Intent.ACTION_VIEW);
  10. Stringtype="video/*";
  11. Uriuri=Uri.parse("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
  12. intent.setDataAndType(uri,type);
  13. instance.startActivity(intent);
  14. }
原文链接:https://www.f2er.com/cocos2dx/339305.html

猜你在找的Cocos2d-x相关文章