cocos2dx 视频播放——VideoPlayer的使用

时间:2021-10-10 09:27:44

转载自:http://www.itnose.net/detail/6188032.html

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

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

HelloWorldScene.h文件

#ifndef __HELLOWORLD_SCENE_H__
#define __HELLOWORLD_SCENE_H__

#include "cocos2d.h"
//务必引入以下2个.h文件
#include "ui/UIVideoPlayer.h"
#include "ui/CocosGUI.h"
USING_NS_CC;
class HelloWorld : public Layer
{
public:
static Scene* createScene();

virtual bool init();

void onEnter();

void videoPlayOverCallback();

void showVideo();
/**
* 视频播放状态,只有在android和ios平台有效
*/
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
void videoEventCallback(Ref* sender, cocos2d::experimental::ui::VideoPlayer::EventType eventType);
#endif

CREATE_FUNC(HelloWorld);
};
#endif


HelloWorldScene.cpp文件 

#include "HelloWorldScene.h"

USING_NS_CC;

Scene* HelloWorld::createScene()
{
auto scene = Scene::create();
auto layer = HelloWorld::create();
scene->addChild(layer);
return scene;
}
bool HelloWorld::init()
{
if ( !Layer::init() )
{
return false;
}
return true;
}

void HelloWorld::onEnter(){
Layer::onEnter();
showVideo();
}

void HelloWorld::showVideo(){
Size size = Director::getInstance()->getVisibleSize();
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
auto videoPlayer = cocos2d::experimental::ui::VideoPlayer::create();
videoPlayer->setPosition(Point(size.width / 2, size.height / 2));
videoPlayer->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
videoPlayer->setContentSize(Size(size.width , size.height));
this->addChild(videoPlayer);
if (videoPlayer)
{
videoPlayer->setFileName("1111.mp4");
videoPlayer->play();
}
videoPlayer->addEventListener(CC_CALLBACK_2(HelloWorld::videoEventCallback, this));
#endif
}

/**
* 视频播放完成的回调函数
*/
void HelloWorld::videoPlayOverCallback()
{

}
/**
* 视频播放的状态
* 注意这里的代码,此处代码只有在android平台和Ios平台有效
*/
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
void HelloWorld::videoEventCallback(Ref* sender, cocos2d::experimental::ui::VideoPlayer::EventType eventType){
switch (eventType) {
case cocos2d::experimental::ui::VideoPlayer::EventType::PLAYING:
break;
case cocos2d::experimental::ui::VideoPlayer::EventType::PAUSED:
break;
case cocos2d::experimental::ui::VideoPlayer::EventType::STOPPED:
break;
case cocos2d::experimental::ui::VideoPlayer::EventType::COMPLETED:
videoPlayOverCallback();
break;
default:
break;
}
}
#endif


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