cocos2dx 3.3 视频播放的实现-VideoPlayer的使用

前端之家收集整理的这篇文章主要介绍了cocos2dx 3.3 视频播放的实现-VideoPlayer的使用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

最近因为项目需求需要使用到视频播放功能

在3.x版本之前如果需要用到视频播放功能就要使用原生的视频播放实现技术,好在3.x之后官方已经集成了视频播放功能,这是值得欣慰的。但是欣慰过后的悲剧在于,官方的文档一直跟不上版本的更新速度。虽然集成了这个功能,但是郁闷的是你要花费很大的力气去尝试使用技巧(仅限于类似我这种菜鸟)。

以下为我整了好久才摸到的使用方法,其实使用不难,难的是一定要注意这个集成的播放器(VideoPlayer)是有平台限制的。一些代码只有在android平台和IOS平台有效。废话不多说了,直接上实例代码

HelloWorldScene.h文件

[cpp] @L_403_0@ copy print ?
  1. #ifndef__HELLOWORLD_SCENE_H__
  2. #define__HELLOWORLD_SCENE_H__
  3. #include"cocos2d.h"
  4. //务必引入以下2个.h文件
  5. #include"ui/UIVideoPlayer.h"
  6. #include"ui/CocosGUI.h"
  7. USING_NS_CC;
  8. classHelloWorld:publicLayer
  9. {
  10. public:
  11. staticScene*createScene();
  12. virtualboolinit();
  13. voidonEnter();
  14. voidvideoPlayOverCallback();
  15. voidshowVideo();
  16. /**
  17. *视频播放状态,只有在android和ios平台有效
  18. */
  19. #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID||CC_TARGET_PLATFORM==CC_PLATFORM_IOS)
  20. voidvideoEventCallback(Ref*sender,cocos2d::experimental::ui::VideoPlayer::EventTypeeventType);
  21. #endif
  22. CREATE_FUNC(HelloWorld);
  23. };
  24. #endif

HelloWorldScene.cpp文件

?

    #include"HelloWorldScene.h"
  1. USING_NS_CC;
  2. Scene*HelloWorld::createScene()
  3. autoscene=Scene::create();
  4. autolayer=HelloWorld::create();
  5. scene->addChild(layer);
  6. returnscene;
  7. }
  8. boolHelloWorld::init()
  9. {
  10. if(!Layer::init())
  11. returnfalse;
  12. returntrue;
  13. voidHelloWorld::onEnter(){
  14. Layer::onEnter();
  15. showVideo();
  16. }
  17. voidHelloWorld::showVideo(){
  18. Sizesize=Director::getInstance()->getVisibleSize();
  19. autovideoPlayer=cocos2d::experimental::ui::VideoPlayer::create();
  20. videoPlayer->setPosition(Point(size.width/2,size.height/2));
  21. videoPlayer->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
  22. videoPlayer->setContentSize(Size(size.width,size.height));
  23. this->addChild(videoPlayer);
  24. if(videoPlayer)
  25. videoPlayer->setFileName("1111.mp4");
  26. videoPlayer->play();
  27. videoPlayer->addEventListener(CC_CALLBACK_2(HelloWorld::videoEventCallback,this));
  28. *视频播放完成的回调函数
  29. voidHelloWorld::videoPlayOverCallback()
  30. /**
  31. *视频播放的状态
  32. *注意这里的代码,此处代码只有在android平台和Ios平台有效
  33. voidHelloWorld::videoEventCallback(Ref*sender,cocos2d::experimental::ui::VideoPlayer::EventTypeeventType){
  34. switch(eventType){
  35. casecocos2d::experimental::ui::VideoPlayer::EventType::PLAYING:
  36. break;
  37. casecocos2d::experimental::ui::VideoPlayer::EventType::PAUSED:
  38. casecocos2d::experimental::ui::VideoPlayer::EventType::STOPPED:
  39. casecocos2d::experimental::ui::VideoPlayer::EventType::COMPLETED:
  40. videoPlayOverCallback();
  41. break;
  42. default:

  43. 如此即可实现视频播放了,对视频的控制请参考官方demo

    ================================下面是另一篇博客的记录========

    Cocos2d-x v2.2.1版本

    下面简单实现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. usingnamespacecocos2d;
  5. classVideoPlatform
  6. {
  7. public:
  8. //在当前的layer上播放视频,视频完毕或者点击跳过视频会跳转到指定的layer上(默认为空,也就是停留在当前layer上)
  9. staticvoidplayVideo(constchar*filename,CCLayer*layer=NULL);
  10. };
  11. #endif//__Platform_H_H__

VideoPlatform.cpp

    #include"VideoPlatform.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. voidVideoPlatform::playVideo( #if(CC_TARGET_PLATFORM==CC_PLATFORM_ANDROID)
  10. //Android视频播放代码
  11. JniMethodInfominfo;
  12. boolisHave=JniHelper::getMethodInfo(minfo,"org/cocos2dx/video/video","playVideo","()V");
  13. if(isHave){
  14. minfo.env->CallStaticVoidMethod(minfo.classID,minfo.methodID);
  15. }
  16. //iOS视频播放代码
  17. IOSPlayVideo::playVideoForIOS(filename,layer);
  18. }

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

IOSPlayVideo.h

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

IOSVideoController.mm

    #import"IOSVideoController.h"
  1. #import"AppController.h"
  2. @implementationIOSVideoController
  3. //播放网络视频
  4. void)playUrlVideo
  5. }
  6. void)playVideo:(NSString*)filename:(CCLayer*)targetLayer
  7. TargetLayer=targetLayer;
  8. //跳转Layer非空
  9. if(targetLayer){
  10. TargetLayer->retain();
  11. SimpleAudioEngine::sharedEngine()->pauseBackgroundMusic();
  12. SimpleAudioEngine::sharedEngine()->pauseAllEffects();
  13. NSString*myFilePath=[[NSBundlemainBundle]pathForResource:filenameofType:nilinDirectory:nil];
  14. NSURL*url=[NSURLfileURLWithPath:myFilePath];
  15. movePlayer=[[MPMoviePlayerControlleralloc]initWithContentURL:url];
  16. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(movieFinished:)name:MPMoviePlayerPlaybackDidFinishNotificationobject:movePlayer];
  17. if([movePlayerrespondsToSelector:@selector(setFullscreen:animated:)])
  18. movePlayer.shouldAutoplay=YES;
  19. CCSizewinSize=CCDirector::sharedDirector()->getWinSize();
  20. CCLog("winSize.width====%fwinSize.height====%f",winSize.width,winSize.height);
  21. //这里iPad2和ipad3视频位置调整是正确的,Iphone可能需要细微调整
  22. if([[UIDevicecurrentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPhone)
  23. movePlayer.view.frame=CGRectMake(-80,80,480,320);
  24. elseif([[UIDevicecurrentDevice]userInterfaceIdiom]==UIUserInterfaceIdiomPad)
  25. movePlayer.view.frame=CGRectMake(-128,128,winSize.height);
  26. else
  27. //强制横屏
  28. CGAffineTransformlandscapeTransform;
  29. UIDevice*device=[UIDevicecurrentDevice];
  30. if(device.orientation==UIDeviceOrientationLandscapeLeft)
  31. landscapeTransform=CGAffineTransformMakeRotation(M_PI/2);
  32. else
  33. landscapeTransform=CGAffineTransformMakeRotation(-M_PI/2);
  34. movePlayer.view.transform=landscapeTransform;
  35. //新建一个window,添加视频这个UIView
  36. window=[[UIWindowalloc]initWithFrame:[[UIScreenmainScreen]bounds]];
  37. [windowaddSubview:movePlayer.view];
  38. [windowmakeKeyAndVisible];
  39. //在视频上方添加“跳过”按钮
  40. CGRectframe=CGRectMake(768-100,100,50);
  41. UIButton*button=[UIButtonbuttonWithType:UIButtonTypeRoundedRect];
  42. button.frame=frame;
  43. [buttonsetTitle:@"跳过"forState:UIControlStateNormal];
  44. button.transform=landscapeTransform;
  45. button.backgroundColor=[UIColorclearColor];
  46. button.tag=2000;
  47. [buttonaddTarget:selfaction:@selector(buttonClicked:)forControlEvents:UIControlEventTouchUpInside];
  48. [windowaddSubview:button];
  49. //设置是否带控制条
  50. movePlayer.controlStyle=MPMovieControlStyleNone;
  51. [[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(exitFullScreen:)name:MPMoviePlayerDidExitFullscreenNotificationobject:nil];
  52. movePlayer.controlStyle=MPMovieControlModeHidden;
  53. [selfplayMovie];
  54. //跳过视频
  55. -(IBAction)buttonClicked:(id)sender{
  56. [movePlayerstop];
  57. [movePlayer.viewremoveFromSuperview];
  58. [movePlayerrelease];
  59. [windowrelease];
  60. SimpleAudioEngine::sharedEngine()->resumeBackgroundMusic();
  61. SimpleAudioEngine::sharedEngine()->resumeAllEffects();
  62. if(!TargetLayer){
  63. return;
  64. TargetLayer->removeAllChildrenWithCleanup(true);
  65. TargetLayer->removeFromParent();
  66. CCScene*scene=CCScene::create();
  67. scene->addChild(TargetLayer,10);
  68. CCDirector::sharedDirector()->replaceScene(scene);
  69. //播放开始
  70. void)playMovie
  71. MPMoviePlaybackStatestate=movePlayer.playbackState;
  72. if(state==MPMoviePlaybackStatePlaying)
  73. NSLog(@"Movieisalreadyplaying.");
  74. [movePlayerplay];
  75. //退出全屏
  76. void)exitFullScreen:(NSNotification*)notification{
  77. CCLOG("exitFullScreen");
  78. movePlayer.controlStyle=MPMovieControlStyleDefault;
  79. [movePlayer.viewremoveFromSuperview];
  80. //视频播放结束
  81. void)movieFinished:(NSNotificationCenter*)notification{
  82. //CCLOG("moviePlaybackFinished");
  83. //视频播放完毕
  84. if(state==MPMoviePlaybackStateStopped){
  85. NSLog(@"Movieisalreadystopped.");
  86. return;
  87. [[NSNotificationCenterdefaultCenter]removeObserver:selfname:MPMoviePlayerPlaybackDidFinishNotificationobject:movePlayer];
  88. [windowrelease];
  89. CCScene*scene=CCScene::create();
  90. scene->addChild(TargetLayer,10);
  91. CCDirector::sharedDirector()->replaceScene(scene);
  92. void)dealloc{
  93. [superdealloc];
  94. if(TargetLayer){
  95. TargetLayer->release();
  96. @end


 

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

[java]
    packageorg.cocos2dx.video;
  1. importandroid.app.Activity;
  2. importandroid.content.pm.ActivityInfo;
  3. importandroid.media.MediaPlayer;
  4. importandroid.net.Uri;
  5. importandroid.os.Bundle;
  6. importandroid.view.Window;
  7. importandroid.view.WindowManager;
  8. importandroid.widget.MediaController;
  9. importandroid.widget.VideoView;
  10. publicclassVideoActivityextendsActivity{
  11. @Override
  12. protectedvoidonCreate(BundlesavedInstanceState){
  13. super.onCreate(savedInstanceState);
  14. requestWindowFeature(Window.FEATURE_NO_TITLE);
  15. getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
  16. WindowManager.LayoutParams.FLAG_FULLSCREEN);
  17. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  18. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);//强制为横屏
  19. setContentView(R.layout.videoview);
  20. finalVideoViewvideoView=(VideoView)findViewById(R.id.VideoView01);
  21. videoView.setVideoURI(Uri.parse("android.resource://"+getPackageName()+"/"+R.raw.theme));
  22. videoView.start();
  23. //视频播控制条设置
  24. MediaControllercontroller=newMediaController(VideoActivity.this);
  25. videoView.setMediaController(controller);
  26. //播放完成监听
  27. videoView.setOnCompletionListener(newMediaPlayer.OnCompletionListener()
  28. @Override
  29. voidonCompletion(MediaPlayermp)
  30. //播放结束后的动作,返回点击播放视频的那个页面
  31. finish();
  32. });
  33. }


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)

    importorg.cocos2dx.lib.Cocos2dxActivity;
  1. importorg.cocos2dx.lib.Cocos2dxGLSurfaceView;
  2. importandroid.content.Intent;
  3. classvideoextendsCocos2dxActivity{
  4. staticvideoinstance;
  5. staticIntentintent;
  6. instance=this;
  7. intent=newIntent(video.this,VideoActivity.class);
  8. voidplayVideo()
  9. instance.startActivity(intent);
  10. publicCocos2dxGLSurfaceViewonCreateView(){
  11. Cocos2dxGLSurfaceViewglSurfaceView=newCocos2dxGLSurfaceView(//videoshouldcreatestencilbuffer
  12. glSurfaceView.setEGLConfigChooser(5,6,0); background-color:inherit">0,0); background-color:inherit">16,0); background-color:inherit">8);
  13. returnglSurfaceView;
  14. static{
  15. System.loadLibrary("cocos2dcpp");
  16. }


至此 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. }
原文链接:https://www.f2er.com/cocos2dx/343960.html

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