Cocos2d-x v2.2.3 IOS,Android “一键式”播放视频

前端之家收集整理的这篇文章主要介绍了Cocos2d-x v2.2.3 IOS,Android “一键式”播放视频前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

参考文献:http://blog.csdn.net/candyforever/article/details/8905852

下面简单实现Cocos2d-x一个视频播放的模块,需要播放视频时,不用到处乱改了,一句代码搞定!

一. IOS播放本地视频

对于IOS平台的视频播放,这里直接使用MediaPlayer.framework来播放视频

注意:MediaPlayer.framework播放视频格式有限,可能需要转换为指定的视频格式才能播放!

1.添加MediaPalyer框架到项目中

2.简单写三个类

VideoPlatform,IOSPlayVideo,IOSVideoController

1)VideoPlatform 这个类用来判断播放视频的平台,从而调用各自平台的视频播放接口

VideoPlatform.h

  1. #ifndef __Platform_H_H__
  2. #define __Platform_H_H__
  3. #include "cocos2d.h"
  4. using namespace cocos2d;
  5. class VideoPlatform
  6. {
  7. public:
  8. //在当前的layer上播放视频,视频完毕或者点击跳过视频会跳转到指定的layer上(默认为空,也就是停留在当前layer上)
  9. static void playVideo(const char * filename,CCLayer *layer =NULL);
  10. };
  11. #endif // __Platform_H_H__


VideoPlatform.cpp

  1. #include "VideoPlatform.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. void VideoPlatform::playVideo(const char * filename,CCLayer *layer)
  11. {
  12. #if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
  13. //Android视频播放代码
  14. JniMethodInfo minfo;
  15. bool isHave = JniHelper::getMethodInfo(minfo,"org/cocos2dx/video/video","playVideo","()V");
  16. if (isHave) {
  17. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
  18. }
  19. #elif(CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  20. //iOS视频播放代码
  21. IOSPlayVideo::playVideoForIOS(filename,layer);
  22. #endif
  23. }


2) IOSPlayVideo是IOS平台播放视频的接口

IOSPlayVideo.h

  1. #ifndef__IOSPlayVideo_H_H__
  2. #define__IOSPlayVideo_H_H__
  3. #include"cocos2d.h"
  4. usingnamespacecocos2d;
  5. classIOSPlayVideo
  6. {
  7. public:
  8. staticvoidplayVideoForIOS(constchar*filename,CCLayer*layer);
  9. };
  10. #endif//__IOSPlayVideo_H_H__

IOSPlayVideo.mm

    #include"IOSPlayVideo.h"
  1. #include"IOSVideoController.h"
  2. voidIOSPlayVideo::playVideoForIOS( //char*转化为NSString
  3. NSString*audioname=[NSStringstringWithUTF8String:filename];
  4. IOSVideoController*app=[[IOSVideoControlleralloc]init];
  5. [appplayVideo:audioname:layer];
  6. }

3)最后IOSVideoController这个类就是ios播放视频的具体实现了

IOSVideoController.h

    #import"MediaPlayer/MediaPlayer.h"
  1. #import"cocos2d.h"
  2. #include"SimpleAudioEngine.h"
  3. namespacecocos2d;
  4. namespaceCocosDenshion;
  5. @interfaceIOSVideoController:MPMoviePlayerViewController
  6. {
  7. MPMoviePlayerController*movePlayer;
  8. UIWindow*window;
  9. CCLayer*TargetLayer;
  10. }
  11. //播放网络视频
  12. -(void)playUrlVideo;
  13. //在当前场景上播放视频,播完或者点击跳过视频到指定的场景
  14. -(void)playVideo:(NSString*)filename:(CCLayer*)targetLayer;
  15. @end

IOSVideoController.mm

  1. #import "IOSVideoController.h"
  2. #import "AppController.h"
  3. @implementation IOSVideoController
  4. //播放网络视频
  5. -(void)playUrlVideo
  6. {
  7. }
  8. -(void)playVideo:(NSString *)filename :(CCLayer *)targetLayer
  9. {
  10. TargetLayer =targetLayer;
  11. //跳转Layer非空
  12. if (targetLayer) {
  13. TargetLayer->retain();
  14. }
  15. SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
  16. SimpleAudioEngine::sharedEngine()->pauseAllEffects();
  17. NSString *myFilePath = [[NSBundle mainBundle] pathForResource:filename ofType:nil inDirectory:nil];
  18. NSURL *url = [NSURL fileURLWithPath:myFilePath];
  19. movePlayer=[[MPMoviePlayerController alloc] initWithContentURL:url];
  20. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(movieFinished:) name:MPMoviePlayerPlaybackDidFinishNotification object:movePlayer];
  21. if([movePlayer respondsToSelector:@selector(setFullscreen:animated:)])
  22. {
  23. movePlayer.shouldAutoplay=YES;
  24. CCSize winSize=CCDirector::sharedDirector()->getWinSize();
  25. CCLog("winSize.width====%f winSize.height====%f",winSize.width,winSize.height);
  26. // 这里iPad2和ipad3 视频位置调整是正确的,Iphone 可能需要细微调整
  27. if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone)
  28. {
  29. movePlayer.view.frame=CGRectMake(-80,80,480,320);
  30. }
  31. else if([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPad)
  32. {
  33. movePlayer.view.frame=CGRectMake(-128,128,winSize.height);
  34. }
  35. else
  36. {
  37. movePlayer.view.frame=CGRectMake(-80,320);
  38. }
  39. // 强制横屏
  40. CGAffineTransform landscapeTransform;
  41. UIDevice *device = [UIDevice currentDevice] ;
  42. if (device.orientation==UIDeviceOrientationLandscapeLeft)
  43. {
  44. landscapeTransform = CGAffineTransformMakeRotation(M_PI / 2);
  45. }
  46. else
  47. {
  48. landscapeTransform = CGAffineTransformMakeRotation(-M_PI / 2);
  49. }
  50. movePlayer.view.transform = landscapeTransform;
  51. // 新建一个window,添加视频这个UIView
  52. window = [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]];
  53. [window addSubview:movePlayer.view];
  54. [window makeKeyAndVisible];
  55. // 在视频上方添加“跳过”按钮
  56. CGRect frame = CGRectMake(768-100,100,50);
  57. UIButton *button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
  58. button.frame = frame;
  59. [button setTitle:@"跳过" forState: UIControlStateNormal];
  60. button.transform =landscapeTransform;
  61. button.backgroundColor = [UIColor clearColor];
  62. button.tag = 2000;
  63. [button addTarget:self action:@selector(buttonClicked:) forControlEvents:UIControlEventTouchUpInside];
  64. [window addSubview:button];
  65. // 设置是否带控制条
  66. movePlayer.controlStyle = MPMovieControlStyleNone;
  67. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(exitFullScreen:) name:MPMoviePlayerDidExitFullscreenNotification object:nil];
  68. }
  69. else
  70. {
  71. movePlayer.controlStyle=MPMovieControlModeHidden;
  72. }
  73. [self playMovie];
  74. }
  75. //跳过视频
  76. -(IBAction) buttonClicked:(id)sender {
  77. [movePlayer stop];
  78. [movePlayer.view removeFromSuperview];
  79. [movePlayer release];
  80. [window release];
  81. SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
  82. SimpleAudioEngine::sharedEngine()->resumeAllEffects();
  83. if (!TargetLayer) {
  84. return;
  85. }
  86. TargetLayer->removeAllChildrenWithCleanup(true);
  87. TargetLayer->removeFromParent();
  88. CCScene * scene =CCScene::create();
  89. scene->addChild(TargetLayer,10);
  90. CCDirector::sharedDirector()->replaceScene(scene);
  91. }
  92. //播放开始
  93. -(void) playMovie
  94. {
  95. MPMoviePlaybackState state=movePlayer.playbackState;
  96. if(state==MPMoviePlaybackStatePlaying)
  97. {
  98. NSLog(@"Movie is already playing.");
  99. return;
  100. }
  101. [movePlayer play];
  102. }
  103. //退出全屏
  104. -(void)exitFullScreen:(NSNotification *)notification{
  105. CCLOG("exitFullScreen");
  106. movePlayer.controlStyle=MPMovieControlStyleDefault;
  107. [movePlayer.view removeFromSuperview];
  108. }
  109. //视频播放结束
  110. - (void) movieFinished:(NSNotificationCenter *)notification{
  111. // CCLOG("moviePlaybackFinished");
  112. //视频播放完毕
  113. movePlayer.controlStyle=MPMovieControlStyleDefault;
  114. MPMoviePlaybackState state=movePlayer.playbackState;
  115. if(state==MPMoviePlaybackStateStopped){
  116. NSLog(@"Movie is already stopped.");
  117. return;
  118. }
  119. [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:movePlayer];
  120. if([movePlayer respondsToSelector:@selector(setFullscreen:animated:)])
  121. {
  122. [movePlayer.view removeFromSuperview];
  123. [window release];
  124. SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
  125. SimpleAudioEngine::sharedEngine()->resumeAllEffects();
  126. if (!TargetLayer) {
  127. return;
  128. }
  129. TargetLayer->removeAllChildrenWithCleanup(true);
  130. TargetLayer->removeFromParent();
  131. CCScene * scene =CCScene::create();
  132. scene->addChild(TargetLayer,10);
  133. CCDirector::sharedDirector()->replaceScene(scene);
  134. }
  135. }
  136. - (void)dealloc {
  137. [super dealloc];
  138. if (TargetLayer) {
  139. TargetLayer->release();
  140. }
  141. }
  142. @end
  1.  

IOS项目里只需在需要的地方调用接口

//只在当前layer上播放视频,播完不跳转就调这个

VideoPlatform::playVideo("test.mp4");

//当前layer上播放视频,播完跳转到指定layer就调这个

VideoPlatform::playVideo("test.mp4",TestLayer::create());

就可以播放视频了!有没有发觉世界瞬间变得美好了一点呢?

二.IOS播放网络视频

只需将

    NSURL*url=[NSURLfileURLWithPath:myFilePath];
类似改为:

    NSURL*url=[NSURLURLWithString:@"http://127.0.0.1/test.mp4"];

(后面填写视频地址就OK!)

三.Android 播放本地视频

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

1) 添加一个VideoActivity

  1. package com.hj.test;
  2. import android.app.Activity;
  3. import android.content.pm.ActivityInfo;
  4. import android.media.MediaPlayer;
  5. import android.net.Uri;
  6. import android.os.Bundle;
  7. import android.view.Window;
  8. import android.view.WindowManager;
  9. import android.widget.MediaController;
  10. import android.widget.VideoView;
  11.  
  12. public class VideoActivity extends Activity {
  13. @Override
  14. protected void onCreate(Bundle savedInstanceState) {
  15. super.onCreate(savedInstanceState);
  16. requestWindowFeature(Window.FEATURE_NO_TITLE);
  17. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
  18. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  19. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
  20. setContentView(R.layout.videoview);
  21. final VideoView videoView = (VideoView)findViewById(R.id.VideoView01);
  22. videoView.setVideoURI(Uri.parse("android.resource://" + getPackageName() + "/" +R.raw.cocosvideo));
  23. videoView.start();
  24. // 视频播控制条设置
  25. MediaController controller = new MediaController(VideoActivity.this);
  26. videoView.setMediaController(controller);
  27. // 播放完成监听
  28. videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
  29. {
  30. @Override
  31. public void onCompletion(MediaPlayer mp)
  32. {
  33. //播放结束后的动作,返回点击播放视频的那个页面
  34. finish();
  35. }
  36. });
  37. }
  38. }

2) 修改AndroidManifest.xml,添加一个Activity

[html]
    <activityandroid:name="VideoActivity"
  1. android:label="@string/app_name"
  2. android:screenOrientation="landscape"
  3. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
  4. android:configChanges="orientation">
  5. intent-filter>
  6. actionandroid:name="android.intent.action.MAIN"/>
  7. categoryandroid:name="android.intent.category.DEFAULT"/>
  8. </activity>


3) 在res /layout添加一个 videoview.xml

    <?xmlversion="1.0"encoding="utf-8"?>
  1. RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent"
  5. android:gravity="center"
  6. tools:context=".VideoActivity"VideoView
  7. android:id="@+id/VideoView01"
  8. android:layout_width="fill_parent"
  9. android:layout_height="fill_parent"
  10. android:layout_alignParentLeft="true"
  11. android:layout_alignParentRight="true"
  12. android:layout_alignParentTop="true"
  13. android:orientation="horizontal"
  14. android:theme="@android:style/Theme.NoTitleBar.Fullscreen"RelativeLayout>


4)在res 下添加一个raw文件夹,里面放你要播放的视频,例如:theme.mp4,这里我的视频文件名为theme


5)修改video.java (我的Android 项目包名为 org.cocos2dx.video)

[java]
    packageorg.cocos2dx.video;
  1. importorg.cocos2dx.lib.Cocos2dxActivity;
  2. importorg.cocos2dx.lib.Cocos2dxGLSurfaceView;
  3. importandroid.content.Intent;
  4. importandroid.os.Bundle;
  5. publicclassvideoextendsCocos2dxActivity{
  6. staticvideoinstance;
  7. staticIntentintent;
  8. protectedvoidonCreate(BundlesavedInstanceState){
  9. super.onCreate(savedInstanceState);
  10. instance=this;
  11. intent=newIntent(video.this,VideoActivity.class);
  12. }
  13. voidplayVideo()
  14. instance.startActivity(intent);
  15. publicCocos2dxGLSurfaceViewonCreateView(){
  16. Cocos2dxGLSurfaceViewglSurfaceView=newCocos2dxGLSurfaceView(this);
  17. //videoshouldcreatestencilbuffer
  18. glSurfaceView.setEGLConfigChooser(5,6,0); background-color:inherit">0,0); background-color:inherit">16,0); background-color:inherit">8);
  19. returnglSurfaceView;
  20. static{
  21. System.loadLibrary("cocos2dcpp");
  22. }


至此 Android播放本地视频就OK了!

四.Android 播放网络视频


添加一个如下方法即可(同样也可以使用JNI C++调Java)

    voidplayURLVideo()
  1. Intentintent=newIntent(Intent.ACTION_VIEW);
  2. Stringtype="video/*";
  3. Uriuri=Uri.parse("http://forum.ea3w.com/coll_ea3w/attach/2008_10/12237832415.3gp");
  4. intent.setDataAndType(uri,type);
  5. instance.startActivity(intent);
  6. }

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