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实现如下:

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

4.添加混编类IOSPlayVideo

IOSPlayVideo.h

[plain] view plain copy
  1. #ifndef__IOSPlayVideo_SCENE_H__
  2. #define__IOSPlayVideo_SCENE_H__
  3. classIOSPlayVideo
  4. {
  5. public:
  6. staticvoidplayVideoForIOS();
  7. };
  8. #endif//__IOSPlayVideo_SCENE_H__

IOSPlayVideo.mm

[plain] view plain copy
  1. #include"IOSPlayVideo.h"
  2. #include"AppController.h"
  3. voidIOSPlayVideo::playVideoForIOS()
  4. {
  5. AppController*app=(AppController*)[[UIApplicationsharedApplication]delegate];
  6. [appplayVideo];
  7. }

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

Platform.h

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


Platform.mm

[plain] view plain copy
  1. #include"Platform.h"
  2. #include"../cocos2dx/platform/CCPlatformConfig.h"
  3. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  4. #include<jni.h>
  5. #include"../cocos2dx/platform/android/jni/JniHelper.h"
  6. #include<android/log.h>
  7. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  8. #include"IOSPlayVideo.h"
  9. #endif
  10. voidPlatform::playVideo()
  11. {
  12. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  13. //Android播放本地视频
  14. JniMethodInfominfo;
  15. boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/playvideo/playvideo","playVedio","()V");
  16. if(isHave)
  17. {
  18. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
  19. }
  20. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  21. //IOS播放本地视频
  22. IOSPlayVideo::playVideoForIOS();
  23. #endif
  24. }
  25. voidPlatform::playURLVideo()
  26. {
  27. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  28. //Android播放网络视频
  29. JniMethodInfominfo;
  30. boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/playvideo/playvideo","playURLVideo","()V");
  31. if(isHave)
  32. {
  33. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
  34. }
  35. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  36. //IOS播放网络视频
  37. IOSPlayVideo::playVideoForIOS();
  38. #endif
  39. }

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

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

A.修改playvideo.java

修改后如下:

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

VideoView.java

[java] view plain copy
  1. packageorg.cocos2dx.playvideo;
  2. importjava.io.IOException;
  3. importandroid.content.Context;
  4. importandroid.content.Intent;
  5. importandroid.media.AudioManager;
  6. importandroid.media.MediaPlayer;
  7. importandroid.media.MediaPlayer.OnCompletionListener;
  8. importandroid.media.MediaPlayer.OnErrorListener;
  9. importandroid.net.Uri;
  10. importandroid.util.AttributeSet;
  11. importandroid.view.KeyEvent;
  12. importandroid.view.MotionEvent;
  13. importandroid.view.SurfaceHolder;
  14. importandroid.view.SurfaceHolder.Callback;
  15. importandroid.view.SurfaceView;
  16. importandroid.view.View;
  17. importandroid.view.ViewGroup.LayoutParams;
  18. importandroid.widget.MediaController;
  19. importandroid.widget.MediaController.MediaPlayerControl;
  20. publicclassVideoViewextendsSurfaceViewimplementsMediaPlayerControl,Callback{
  21. privateContextmContext;
  22. //settablebytheclient
  23. privateUrimUri;
  24. privateintmDuration;
  25. //Allthestuffweneedforplayingandshowingavideo
  26. privateSurfaceHoldermSurfaceHolder=null;
  27. privateMediaPlayermMediaPlayer=null;
  28. privatebooleanmIsPrepared;
  29. privateintmVideoWidth;
  30. privateintmVideoHeight;
  31. privateintmSurfaceWidth;
  32. privateintmSurfaceHeight;
  33. privateMediaControllermMediaController;
  34. privateOnCompletionListenermOnCompletionListener;
  35. privateMediaPlayer.OnPreparedListenermOnPreparedListener;
  36. privateintmCurrentBufferPercentage;
  37. privateOnErrorListenermOnErrorListener;
  38. privatebooleanmStartWhenPrepared;
  39. privateintmSeekWhenPrepared;
  40. privateMySizeChangeLinstenermMyChangeLinstener;
  41. publicintgetVideoWidth(){
  42. returnmVideoWidth;
  43. }
  44. publicintgetVideoHeight(){
  45. returnmVideoHeight;
  46. }
  47. publicvoidsetVideoScale(intwidth,intheight){
  48. LayoutParamslp=getLayoutParams();
  49. lp.height=height;
  50. lp.width=width;
  51. setLayoutParams(lp);
  52. }
  53. publicinterfaceMySizeChangeLinstener{
  54. publicvoiddoMyThings();
  55. }
  56. publicvoidsetMySizeChangeLinstener(MySizeChangeLinstenerl){
  57. mMyChangeLinstener=l;
  58. }
  59. publicVideoView(Contextcontext){
  60. super(context);
  61. mContext=context;
  62. initVideoView();
  63. }
  64. publicVideoView(Contextcontext,AttributeSetattrs){
  65. this(context,attrs,0);
  66. mContext=context;
  67. initVideoView();
  68. }
  69. publicVideoView(Contextcontext,AttributeSetattrs,intdefStyle){
  70. super(context,attrs,defStyle);
  71. mContext=context;
  72. initVideoView();
  73. }
  74. @Override
  75. protectedvoidonMeasure(intwidthMeasureSpec,intheightMeasureSpec){
  76. //Log.i("@@@@","onMeasure");
  77. intwidth=getDefaultSize(mVideoWidth,widthMeasureSpec);
  78. intheight=getDefaultSize(mVideoHeight,heightMeasureSpec);
  79. /*
  80. *if(mVideoWidth>0&&mVideoHeight>0){if(mVideoWidth*height
  81. *>width*mVideoHeight){//Log.i("@@@",
  82. *"imagetootall,correcting");height=width*mVideoHeight/
  83. *mVideoWidth;}elseif(mVideoWidth*height<width*mVideoHeight
  84. *){//Log.i("@@@","imagetoowide,correcting");width=height*
  85. *mVideoWidth/mVideoHeight;}else{//Log.i("@@@",
  86. *"aspectratioiscorrect:"+//width+"/"+height+"="+
  87. *//mVideoWidth+"/"+mVideoHeight);}}
  88. */
  89. //Log.i("@@@@@@@@@@","settingsize:"+width+'x'+height);
  90. setMeasuredDimension(width,height);
  91. }
  92. publicintresolveAdjustedSize(intdesiredSize,intmeasureSpec){
  93. intresult=desiredSize;
  94. intspecMode=MeasureSpec.getMode(measureSpec);
  95. intspecSize=MeasureSpec.getSize(measureSpec);
  96. switch(specMode){
  97. caseMeasureSpec.UNSPECIFIED:
  98. /*
  99. *Parentsayswecanbeasbigaswewant.Justdon'tbelarger
  100. *thanmaxsizeimposedonourselves.
  101. */
  102. result=desiredSize;
  103. break;
  104. caseMeasureSpec.AT_MOST:
  105. /*
  106. *Parentsayswecanbeasbigaswewant,uptospecSize.Don'tbe
  107. *largerthanspecSize,anddon'tbelargerthanthemaxsize
  108. *imposedonourselves.
  109. */
  110. result=Math.min(desiredSize,specSize);
  111. break;
  112. caseMeasureSpec.EXACTLY:
  113. //Nochoice.Dowhatwearetold.
  114. result=specSize;
  115. break;
  116. }
  117. returnresult;
  118. }
  119. privatevoidinitVideoView(){
  120. mVideoWidth=0;
  121. mVideoHeight=0;
  122. getHolder().addCallback(this);
  123. getHolder().setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
  124. setFocusable(true);
  125. setFocusableInTouchMode(true);
  126. requestFocus();
  127. }
  128. publicvoidsetVideoPath(Stringpath){
  129. setVideoURI(Uri.parse(path));
  130. }
  131. publicvoidsetVideoURI(Uriuri){
  132. mUri=uri;
  133. mStartWhenPrepared=false;
  134. mSeekWhenPrepared=0;
  135. openVideo();
  136. requestLayout();
  137. invalidate();
  138. }
  139. publicvoidstopPlayback(){
  140. if(mMediaPlayer!=null){
  141. mMediaPlayer.stop();
  142. mMediaPlayer.release();
  143. mMediaPlayer=null;
  144. }
  145. }
  146. privatevoidopenVideo(){
  147. if(mUri==null||mSurfaceHolder==null){
  148. //notreadyforplaybackjustyet,willtryagainlater
  149. return;
  150. }
  151. //Tellthemusicplaybackservicetopause
  152. //TODO:theseconstantsneedtobepublishedsomewhereinthe
  153. //framework.
  154. Intenti=newIntent("com.android.music.musicservicecommand");
  155. i.putExtra("command","pause");
  156. mContext.sendBroadcast(i);
  157. if(mMediaPlayer!=null){
  158. mMediaPlayer.reset();
  159. mMediaPlayer.release();
  160. mMediaPlayer=null;
  161. }
  162. try{
  163. mMediaPlayer=newMediaPlayer();
  164. mMediaPlayer.setOnPreparedListener(mPreparedListener);
  165. mMediaPlayer.setOnVideoSizeChangedListener(mSizeChangedListener);
  166. mIsPrepared=false;
  167. //Log.v(TAG,"resetdurationto-1inopenVideo");
  168. mDuration=-1;
  169. mMediaPlayer.setOnCompletionListener(mCompletionListener);
  170. mMediaPlayer.setOnErrorListener(mErrorListener);
  171. mMediaPlayer.setOnBufferingUpdateListener(mBufferingUpdateListener);
  172. mCurrentBufferPercentage=0;
  173. mMediaPlayer.setDataSource(mContext,mUri);
  174. mMediaPlayer.setDisplay(mSurfaceHolder);
  175. mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
  176. mMediaPlayer.setScreenOnWhilePlaying(true);
  177. mMediaPlayer.prepareAsync();
  178. attachMediaController();
  179. }catch(IOExceptionex){
  180. //Log.w(TAG,"Unabletoopencontent:"+mUri,ex);
  181. return;
  182. }catch(IllegalArgumentExceptionex){
  183. //Log.w(TAG,"Unabletoopencontent:"+mUri,ex);
  184. return;
  185. }
  186. }
  187. publicvoidsetMediaController(MediaControllercontroller){
  188. if(mMediaController!=null){
  189. mMediaController.hide();
  190. }
  191. mMediaController=controller;
  192. attachMediaController();
  193. }
  194. privatevoidattachMediaController(){
  195. if(mMediaPlayer!=null&&mMediaController!=null){
  196. mMediaController.setMediaPlayer(this);
  197. ViewanchorView=this.getParent()instanceofView?(View)this
  198. .getParent():this;
  199. mMediaController.setAnchorView(anchorView);
  200. mMediaController.setEnabled(mIsPrepared);
  201. }
  202. }
  203. MediaPlayer.OnVideoSizeChangedListenermSizeChangedListener=newMediaPlayer.OnVideoSizeChangedListener(){
  204. publicvoidonVideoSizeChanged(MediaPlayermp,intwidth,intheight){
  205. mVideoWidth=mp.getVideoWidth();
  206. mVideoHeight=mp.getVideoHeight();
  207. if(mMyChangeLinstener!=null){
  208. mMyChangeLinstener.doMyThings();
  209. }
  210. if(mVideoWidth!=0&&mVideoHeight!=0){
  211. getHolder().setFixedSize(mVideoWidth,mVideoHeight);
  212. }
  213. }
  214. };
  215. MediaPlayer.OnPreparedListenermPreparedListener=newMediaPlayer.OnPreparedListener(){
  216. publicvoidonPrepared(MediaPlayermp){
  217. //brieflyshowthemediacontroller
  218. mIsPrepared=true;
  219. if(mOnPreparedListener!=null){
  220. mOnPreparedListener.onPrepared(mMediaPlayer);
  221. }
  222. if(mMediaController!=null){
  223. mMediaController.setEnabled(true);
  224. }
  225. mVideoWidth=mp.getVideoWidth();
  226. mVideoHeight=mp.getVideoHeight();
  227. if(mVideoWidth!=0&&mVideoHeight!=0){
  228. //Log.i("@@@@","videosize:"+mVideoWidth+"/"+
  229. //mVideoHeight);
  230. getHolder().setFixedSize(mVideoWidth,mVideoHeight);
  231. if(mSurfaceWidth==mVideoWidth
  232. &&mSurfaceHeight==mVideoHeight){
  233. //Wedidn'tactuallychangethesize(itwasalreadyatthe
  234. //size
  235. //weneed),sowewon'tgeta"surfacechanged"callback,
  236. //so
  237. //startthevideohereinsteadofinthecallback.
  238. if(mSeekWhenPrepared!=0){
  239. mMediaPlayer.seekTo(mSeekWhenPrepared);
  240. mSeekWhenPrepared=0;
  241. }
  242. if(mStartWhenPrepared){
  243. mMediaPlayer.start();
  244. mStartWhenPrepared=false;
  245. if(mMediaController!=null){
  246. mMediaController.show();
  247. }
  248. }elseif(!isPlaying()
  249. &&(mSeekWhenPrepared!=0||getCurrentPosition()>0)){
  250. if(mMediaController!=null){
  251. //Showthemediacontrolswhenwe'repausedintoa
  252. //videoandmake'emstick.
  253. mMediaController.show(0);
  254. }
  255. }
  256. }
  257. }else{
  258. //Wedon'tknowthevideosizeyet,butshouldstartanyway.
  259. //Thevideosizemightbereportedtouslater.
  260. if(mSeekWhenPrepared!=0){
  261. mMediaPlayer.seekTo(mSeekWhenPrepared);
  262. mSeekWhenPrepared=0;
  263. }
  264. if(mStartWhenPrepared){
  265. mMediaPlayer.start();
  266. mStartWhenPrepared=false;
  267. }
  268. }
  269. }
  270. };
  271. privateMediaPlayer.OnCompletionListenermCompletionListener=newMediaPlayer.OnCompletionListener(){
  272. publicvoidonCompletion(MediaPlayermp){
  273. if(mMediaController!=null){
  274. mMediaController.hide();
  275. }
  276. if(mOnCompletionListener!=null){
  277. mOnCompletionListener.onCompletion(mMediaPlayer);
  278. }
  279. }
  280. };
  281. privateMediaPlayer.OnErrorListenermErrorListener=newMediaPlayer.OnErrorListener(){
  282. publicbooleanonError(MediaPlayermp,intframework_err,intimpl_err){
  283. //Log.d(TAG,"Error:"+framework_err+","+impl_err);
  284. if(mMediaController!=null){
  285. mMediaController.hide();
  286. }
  287. /*Ifanerrorhandlerhasbeensupplied,useitandfinish.*/
  288. if(mOnErrorListener!=null){
  289. if(mOnErrorListener.onError(mMediaPlayer,framework_err,
  290. impl_err)){
  291. returntrue;
  292. }
  293. }
  294. /*
  295. *Otherwise,popupanerrordialogsotheuserknowsthat
  296. *somethingbadhashappened.Onlytryandpopupthedialogif
  297. *we'reattachedtoawindow.Whenwe'regoingawayandnolonger
  298. *haveawindow,don'tbothershowingtheuseranerror.
  299. */
  300. if(getWindowToken()!=null){
  301. /*
  302. *if(framework_err==
  303. *MediaPlayer.MEDIA_ERROR_NOT_VALID_FOR_PROGRESSIVE_PLAYBACK){
  304. *messageId=com.android.internal.R.string.
  305. *VideoView_error_text_invalid_progressive_playback;}else{
  306. *messageId=
  307. *com.android.internal.R.string.VideoView_error_text_unknown;}
  308. *
  309. *newAlertDialog.Builder(mContext)
  310. *.setTitle(com.android.internal
  311. *.R.string.VideoView_error_title).setMessage(messageId)
  312. *.setPositiveButton
  313. *(com.android.internal.R.string.VideoView_error_button,new
  314. *DialogInterface.OnClickListener(){publicvoid
  315. *onClick(DialogInterfacedialog,intwhichButton){Ifweget
  316. *here,thereisnoonErrorlistener,soatleastinformthem
  317. *thatthevideoisover.
  318. *
  319. *if(mOnCompletionListener!=null){
  320. *mOnCompletionListener.onCompletion(mMediaPlayer);}}})
  321. *.setCancelable(false).show();
  322. */
  323. }
  324. returntrue;
  325. }
  326. };
  327. privateMediaPlayer.OnBufferingUpdateListenermBufferingUpdateListener=newMediaPlayer.OnBufferingUpdateListener(){
  328. publicvoidonBufferingUpdate(MediaPlayermp,intpercent){
  329. mCurrentBufferPercentage=percent;
  330. }
  331. };
  332. /**
  333. *Registeracallbacktobeinvokedwhenthemediafileisloadedandready
  334. *togo.
  335. *
  336. *@paraml
  337. *Thecallbackthatwillberun
  338. */
  339. publicvoidsetOnPreparedListener(MediaPlayer.OnPreparedListenerl){
  340. mOnPreparedListener=l;
  341. }
  342. /**
  343. *Registeracallbacktobeinvokedwhentheendofamediafilehasbeen
  344. *reachedduringplayback.
  345. *
  346. *@paraml
  347. *Thecallbackthatwillberun
  348. */
  349. publicvoidsetOnCompletionListener(OnCompletionListenerl){
  350. mOnCompletionListener=l;
  351. }
  352. /**
  353. *Registeracallbacktobeinvokedwhenanerroroccursduringplaybackor
  354. *setup.Ifnolistenerisspecified,orifthelistenerreturnedfalse,
  355. *VideoViewwillinformtheuserofanyerrors.
  356. *
  357. *@paraml
  358. *Thecallbackthatwillberun
  359. */
  360. publicvoidsetOnErrorListener(OnErrorListenerl){
  361. mOnErrorListener=l;
  362. }
  363. @Override
  364. publicbooleanonTouchEvent(MotionEventev){
  365. if(mIsPrepared&&mMediaPlayer!=null&&mMediaController!=null){
  366. toggleMediaControlsVisiblity();
  367. }
  368. returnfalse;
  369. }
  370. @Override
  371. publicbooleanonTrackballEvent(MotionEventev){
  372. if(mIsPrepared&&mMediaPlayer!=null&&mMediaController!=null){
  373. toggleMediaControlsVisiblity();
  374. }
  375. returnfalse;
  376. }
  377. @Override
  378. publicbooleanonKeyDown(intkeyCode,KeyEventevent){
  379. if(mIsPrepared&&keyCode!=KeyEvent.KEYCODE_BACK
  380. &&keyCode!=KeyEvent.KEYCODE_VOLUME_UP
  381. &&keyCode!=KeyEvent.KEYCODE_VOLUME_DOWN
  382. &&keyCode!=KeyEvent.KEYCODE_MENU
  383. &&keyCode!=KeyEvent.KEYCODE_CALL
  384. &&keyCode!=KeyEvent.KEYCODE_ENDCALL&&mMediaPlayer!=null
  385. &&mMediaController!=null){
  386. if(keyCode==KeyEvent.KEYCODE_HEADSETHOOK
  387. ||keyCode==KeyEvent.KEYCODE_MEDIA_PLAY_PAUSE){
  388. if(mMediaPlayer.isPlaying()){
  389. pause();
  390. mMediaController.show();
  391. }else{
  392. start();
  393. mMediaController.hide();
  394. }
  395. returntrue;
  396. }elseif(keyCode==KeyEvent.KEYCODE_MEDIA_STOP
  397. &&mMediaPlayer.isPlaying()){
  398. pause();
  399. mMediaController.show();
  400. }else{
  401. toggleMediaControlsVisiblity();
  402. }
  403. }
  404. returnsuper.onKeyDown(keyCode,event);
  405. }
  406. privatevoidtoggleMediaControlsVisiblity(){
  407. if(mMediaController.isShowing()){
  408. mMediaController.hide();
  409. }else{
  410. mMediaController.show();
  411. }
  412. }
  413. publicvoidstart(){
  414. if(mMediaPlayer!=null&&mIsPrepared){
  415. mMediaPlayer.start();
  416. mStartWhenPrepared=false;
  417. }else{
  418. mStartWhenPrepared=true;
  419. }
  420. }
  421. publicvoidpause(){
  422. if(mMediaPlayer!=null&&mIsPrepared){
  423. if(mMediaPlayer.isPlaying()){
  424. mMediaPlayer.pause();
  425. }
  426. }
  427. mStartWhenPrepared=false;
  428. }
  429. publicintgetDuration(){
  430. if(mMediaPlayer!=null&&mIsPrepared){
  431. if(mDuration>0){
  432. returnmDuration;
  433. }
  434. mDuration=mMediaPlayer.getDuration();
  435. returnmDuration;
  436. }
  437. mDuration=-1;
  438. returnmDuration;
  439. }
  440. publicintgetCurrentPosition(){
  441. if(mMediaPlayer!=null&&mIsPrepared){
  442. returnmMediaPlayer.getCurrentPosition();
  443. }
  444. return0;
  445. }
  446. publicvoidseekTo(intmsec){
  447. if(mMediaPlayer!=null&&mIsPrepared){
  448. mMediaPlayer.seekTo(msec);
  449. }else{
  450. mSeekWhenPrepared=msec;
  451. }
  452. }
  453. publicbooleanisPlaying(){
  454. if(mMediaPlayer!=null&&mIsPrepared){
  455. returnmMediaPlayer.isPlaying();
  456. }
  457. returnfalse;
  458. }
  459. publicintgetBufferPercentage(){
  460. if(mMediaPlayer!=null){
  461. returnmCurrentBufferPercentage;
  462. }
  463. return0;
  464. }
  465. publicvoidsurfaceChanged(SurfaceHolderholder,intformat,intwidth,
  466. intheight){
  467. mSurfaceWidth=width;
  468. mSurfaceHeight=height;
  469. if(mMediaPlayer!=null&&mIsPrepared&&mVideoWidth==width
  470. &&mVideoHeight==height){
  471. if(mSeekWhenPrepared!=0){
  472. mMediaPlayer.seekTo(mSeekWhenPrepared);
  473. mSeekWhenPrepared=0;
  474. }
  475. mMediaPlayer.start();
  476. if(mMediaController!=null){
  477. mMediaController.show();
  478. }
  479. }
  480. }
  481. publicvoidsurfaceCreated(SurfaceHolderholder){
  482. mSurfaceHolder=holder;
  483. openVideo();
  484. }
  485. publicvoidsurfaceDestroyed(SurfaceHolderholder){
  486. //afterwereturnfromthiswecan'tusethesurfaceanymore
  487. mSurfaceHolder=null;
  488. if(mMediaController!=null)
  489. mMediaController.hide();
  490. if(mMediaPlayer!=null){
  491. mMediaPlayer.reset();
  492. mMediaPlayer.release();
  493. mMediaPlayer=null;
  494. }
  495. }
  496. publicbooleancanPause(){
  497. //TODOAuto-generatedmethodstub
  498. returnfalse;
  499. }
  500. publicbooleancanSeekBackward(){
  501. //TODOAuto-generatedmethodstub
  502. returnfalse;
  503. }
  504. publicbooleancanSeekForward(){
  505. //TODOAuto-generatedmethodstub
  506. returnfalse;
  507. }
  508. }
VedioActivity.java

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

二.播放网络视频

IOS项目:

在RootViewController.h里添加playURLVideo函数

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

RootViewController.mm实现playURLVideo函数如下:

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

然后修改AppController.mm里的函数

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

Android项目:修改playvideo.java

修改后如下:

[java] view plain copy
  1. packageorg.cocos2dx.playvideo;
  2. importorg.cocos2dx.lib.Cocos2dxActivity;
  3. importandroid.net.Uri;
  4. importandroid.os.Bundle;
  5. importandroid.content.Intent;
  6. publicclassplayvideoextendsCocos2dxActivity{
  7. //当前类实例
  8. publicstaticplayvideoinstance;
  9. //用于切换Activity
  10. publicstaticIntentintent;
  11. publicvoidonCreate(BundlesavedInstanceState){
  12. super.onCreate(savedInstanceState);
  13. instance=this;
  14. }
  15. voidplayURLVideo()
  16. {
  17. Intentintent=newIntent(Intent.ACTION_VIEW);
  18. Stringtype="video/*";
  19. Uriuri=Uri.parse("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
  20. intent.setDataAndType(uri,type);
  21. instance.startActivity(intent);
  22. }
  23. static{
  24. System.loadLibrary("game");
  25. }
  26. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值