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

修改后如下:

[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. }

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


    本文实践自 RayWenderlich、Ali Hafizji 的文章《How To Create Dynamic Textures with CCRenderTexture in Cocos2D 2.X》,文中使用Cocos2D,我在这里使用Cocos2D-x 2.1.4进行学习和移植。在这篇文章,将会学习到如何创建实时纹理、如何用Gimp创建无缝拼接纹
Cocos-code-ide使用入门学习地点:杭州滨江邮箱:appdevzw@163.com微信公众号:HopToad 欢迎转载,转载标注出处:http://blog.csdn.netotbaron/article/details/424343991.  软件准备 下载地址:http://cn.cocos2d-x.org/download 2.  简介2.1         引用C
第一次開始用手游引擎挺激动!!!进入正题。下载资源1:从Cocos2D-x官网上下载,进入网页http://www.cocos2d-x.org/download,点击Cocos2d-x以下的Download  v3.0,保存到自定义的文件夹2:从python官网上下载。进入网页https://www.python.org/downloads/,我当前下载的是3.4.0(当前最新
    Cocos2d-x是一款强大的基于OpenGLES的跨平台游戏开发引擎,易学易用,支持多种智能移动平台。官网地址:http://cocos2d-x.org/当前版本:2.0    有很多的学习资料,在这里我只做为自己的笔记记录下来,错误之处还请指出。在VisualStudio2008平台的编译:1.下载当前稳
1.  来源 QuickV3sample项目中的2048样例游戏,以及最近《最强大脑》娱乐节目。将2048改造成一款挑战玩家对数字记忆的小游戏。邮箱:appdevzw@163.com微信公众号:HopToadAPK下载地址:http://download.csdn.net/detailotbaron/8446223源码下载地址:http://download.csdn.net/
   Cocos2d-x3.x已经支持使用CMake来进行构建了,这里尝试以QtCreatorIDE来进行CMake构建。Cocos2d-x3.X地址:https://github.com/cocos2d/cocos2d-x1.打开QtCreator,菜单栏→"打开文件或项目...",打开cocos2d-x目录下的CMakeLists.txt文件;2.弹出CMake向导,如下图所示:设置
 下载地址:链接:https://pan.baidu.com/s/1IkQsMU6NoERAAQLcCUMcXQ提取码:p1pb下载完成后,解压进入build目录使用vs2013打开工程设置平台工具集,打开设置界面设置: 点击开始编译等待编译结束编译成功在build文件下会出现一个新文件夹Debug.win32,里面就是编译
分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!http://www.captainbed.net前言上次用象棋演示了cocos2dx的基本用法,但是对cocos2dx并没有作深入的讨论,这次以超级马里奥的源代码为线索,我们一起来学习超级马里奥的实
1. 圆形音量button事实上作者的本意应该是叫做“电位计button”。可是我觉得它和我们的圆形音量button非常像,所以就这么叫它吧~先看效果:好了,不多解释,本篇到此为止。(旁白: 噗。就这样结束了?)啊才怪~我们来看看代码:[cpp] viewplaincopyprint?CCContro
原文链接:http://www.cnblogs.com/physwf/archive/2013/04/26/3043912.html为了进一步深入学习贯彻Cocos2d,我们将自己写一个场景类,但我们不会走的太远,凡是都要循序渐进,哪怕只前进一点点,那也至少是前进了,总比贪多嚼不烂一头雾水的好。在上一节中我们建
2019独角兽企业重金招聘Python工程师标准>>>cocos2d2.0之后加入了一种九宫格的实现,主要作用是用来拉伸图片,这样的好处在于保留图片四个角不变形的同时,对图片中间部分进行拉伸,来满足一些控件的自适应(PS: 比如包括按钮,对话框,最直观的形象就是ios里的短信气泡了),这就要求图
原文链接:http://www.cnblogs.com/linji/p/3599478.html1.环境和工具准备Win7VS2010/2012,至于2008v2版本之后似乎就不支持了。 2.安装pythonv.2.0版本之前是用vs模板创建工程的,到vs2.2之后就改用python创建了。到python官网下载版本2.7.5的,然后
环境:ubuntu14.04adt-bundle-linux-x86_64android-ndk-r9d-linux-x86_64cocos2d-x-3.0正式版apache-ant1.9.3python2.7(ubuntu自带)加入环境变量exportANDROID_SDK_ROOT=/home/yangming/adt-bundle-linux/sdkexportPATH=${PATH}:/$ANDROID_SDK_ROOTools/export
1开发背景游戏程序设计涉及了学科中的各个方面,鉴于目的在于学习与进步,本游戏《FlappyBird》采用了两个不同的开发方式来开发本款游戏,一类直接采用win32底层API来实现,另一类采用当前火热的cocos2d-x游戏引擎来开发本游戏。2需求分析2.1数据分析本项目要开发的是一款游
原文链接:http://www.cnblogs.com/linji/p/3599912.html//纯色色块控件(锚点默认左下角)CCLayerColor*ccc=CCLayerColor::create(ccc4(255,0,0,128),200,100);//渐变色块控件CCLayerGradient*ccc=CCLayerGradient::create(ccc4(255,0,0,
原文链接:http://www.cnblogs.com/linji/p/3599488.html//载入一张图片CCSprite*leftDoor=CCSprite::create("loading/door.png");leftDoor->setAnchorPoint(ccp(1,0.5));//设置锚点为右边中心点leftDoor->setPosition(ccp(240,160));/
为了答谢广大学员对智捷课堂以及关老师的支持,现购买51CTO学院关老师的Cocos2d-x课程之一可以送智捷课堂编写图书一本(专题可以送3本)。一、Cocos2d-x课程列表:1、Cocos2d-x入门与提高视频教程__Part22、Cocos2d-x数据持久化与网络通信__Part33、Cocos2d-x架构设计与性能优化内存优
Spawn让多个action同时执行。Spawn有多种不同的create方法,最终都调用了createWithTwoActions(FiniteTimeAction*action1,FiniteTimeAction*action2)方法。createWithTwoActions调用initWithTwoActions方法:对两个action变量初始化:_one=action1;_two=action2;如果两个a
需要环境:php,luajit.昨天在cygwin上安装php和luajit环境,这真特么是一个坑。建议不要用虚拟环境安装打包环境,否则可能会出现各种莫名问题。折腾了一下午,最终将环境转向linux。其中,luajit的安装脚本已经在quick-cocos2d-x-develop/bin/中,直接luajit_install.sh即可。我的lin
v3.0相对v2.2来说,最引人注意的。应该是对触摸层级的优化。和lambda回调函数的引入(嗯嗯,不枉我改了那么多类名。话说,每次cocos2dx大更新。总要改掉一堆类名函数名)。这些特性应该有不少人研究了,所以今天说点跟图片有关的东西。v3.0在载入图片方面也有了非常大改变,仅仅只是