最近因为项目需求需要使用到视频播放功能。
在3.x版本之前如果需要用到视频播放功能就要使用原生的视频播放实现技术,好在3.x之后官方已经集成了视频播放功能,这是值得欣慰的。但是欣慰过后的悲剧在于,官方的文档一直跟不上版本的更新速度。虽然集成了这个功能,但是郁闷的是你要花费很大的力气去尝试使用技巧(仅限于类似我这种菜鸟)。
以下为我整了好久才摸到的使用方法,其实使用不难,难的是一定要注意这个集成的播放器(VideoPlayer)是有平台限制的。一些代码只有在android平台和IOS平台有效。废话不多说了,直接上实例代码:
HelloWorldScene.h文件
01.#ifndef
__HELLOWORLD_SCENE_H__
02.#define
__HELLOWORLD_SCENE_H__
03.
04.#include "cocos2d.h"
05.//务必引入以下2个.h文件
06.#include "ui/UIVideoPlayer.h"
07.#include "ui/CocosGUI.h"
08.USING_NS_CC;
09.class HelloWorld
: public Layer
10.{
11.public:
12.static Scene*
createScene();
13.
14.virtual
bool init();
15.
16.void onEnter();
17.
18.void videoPlayOverCallback();
19.
20.void showVideo();
21./**
22.*
视频播放状态,只有在android和ios平台有效
23.*/
24.#if (CC_TARGET_PLATFORM
== CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
25.void videoEventCallback(Ref*
sender, cocos2d::experimental::ui::VideoPlayer::EventType eventType);
26.#endif
27.
28.CREATE_FUNC(HelloWorld);
29.};
30.#endif
HelloWorldScene.cpp文件
01.#include "HelloWorldScene.h"
02.
03.USING_NS_CC;
04.
05.Scene*
HelloWorld::createScene()
06.{
07.auto
scene = Scene::create();
08.auto
layer = HelloWorld::create();
09.scene->addChild(layer);
10.return scene;
11.}
12.bool
HelloWorld::init()
13.{
14.if (
!Layer::init() )
15.{
16.return false;
17.}
18.return true;
19.}
20.
21.void HelloWorld::onEnter(){
22.Layer::onEnter();
23.showVideo();
24.}
25.
26.void HelloWorld::showVideo(){
27.Size
size = Director::getInstance()->getVisibleSize();
28.#if (CC_TARGET_PLATFORM
== CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
29.auto
videoPlayer = cocos2d::experimental::ui::VideoPlayer::create();
30.videoPlayer->setPosition(Point(size.width
/ 2,
size.height / 2));
31.videoPlayer->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
32.videoPlayer->setContentSize(Size(size.width
, size.height));
33.this->addChild(videoPlayer);
34.if (videoPlayer)
35.{
36.videoPlayer->setFileName("1111.mp4");
37.videoPlayer->play();
38.}
39.videoPlayer->addEventListener(CC_CALLBACK_2(HelloWorld::videoEventCallback, this));
40.#endif
41.}
42.
43./**
44.*
视频播放完成的回调函数
45.*/
46.void HelloWorld::videoPlayOverCallback()
47.{
48.
49.}
50./**
51.*
视频播放的状态
52.*
注意这里的代码,此处代码只有在android平台和Ios平台有效
53.*/
54.#if (CC_TARGET_PLATFORM
== CC_PLATFORM_ANDROID || CC_TARGET_PLATFORM == CC_PLATFORM_IOS)
55.void HelloWorld::videoEventCallback(Ref*
sender, cocos2d::experimental::ui::VideoPlayer::EventType eventType){
56.switch (eventType)
{
57.case cocos2d::experimental::ui::VideoPlayer::EventType::PLAYING:
58.break;
59.case cocos2d::experimental::ui::VideoPlayer::EventType::PAUSED:
60.break;
61.case cocos2d::experimental::ui::VideoPlayer::EventType::STOPPED:
62.break;
63.case cocos2d::experimental::ui::VideoPlayer::EventType::COMPLETED:
64.videoPlayOverCallback();
65.break;
66.default:
67.break;
68.}
69.}
70.#endif