1. 程式人生 > >cocos2d-x 3.0 播放MP4視頻

cocos2d-x 3.0 播放MP4視頻

獲取 cocos2 con selector lba 技術 root csdn 移除

猴子原創,歡迎轉載。

轉載請註明: 轉載自Cocos2D開發網–Cocos2Dev.com,謝謝。

原文地址: http://www.cocos2dev.com/?p=545

非常久曾經寫的一個2dx播放MP4視頻的教材。有網友反映已經不能用了,今天晚上寫了個簡單的2dx播放視頻類。使用的是cocos2dx 3.0。

技術分享

類說明:
LHVideoPlayerImplCpp.h/mm // cocos2dx中使用的播放MP4接口
LHVideoPlayerImpl.h/m // videoPlayer的oc接口
LHVideoPlayer.h/m // videoPlayer的實現。調用MPMoviePlayerController播放MP4
LHVideoOverlayView.h/m // videoPlayer的上層操作層,有跳過影片button。

我就功能點而言,介紹當中的兩個類。

第一個是LHVideoPlayerImplCpp.h/mm文件。這個是負責給2dx調用的。

該類有兩個靜態方法:

class LHVideoPlayerImplCpp {
public:
    /**
     * 開始播放MP4視頻
     * name 視頻名稱。不要帶後綴".mp4"。

(比方文件是test.mp4, 那麽name就傳"test") * frameRect 視頻顯示的區域。全屏(Rect(0, 0, visibleSize.width, visibleSize.height)) */ static void playMP4WithName(const char* name, cocos2d::Rect frameRect); /** * 設置跳過影片buttontitle,默認無跳過影片功能 */ static void setSkipTitle(const char* title); };


第二個是LHVideoPlayer.h/m,這個是負責播放MP4。
1、這種方法是播放MP4。凝視非常清楚。

- (void)playMP4WithName: (NSString *)name VideoFrame:(CGRect)rect
{
    UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
    
    // 獲取視頻文件的名稱
    NSString *url = [[NSBundle mainBundle]pathForResource:name ofType:@"mp4"];
    // 初始化player
    _player = [[MPMoviePlayerController alloc] initWithContentURL:[NSURL fileURLWithPath:url]];
    [keyWindow.rootViewController.view addSubview: [_player view]];
    
    // 設置player樣式
    [_player setControlStyle: MPMovieControlStyleNone];
    [[_player view] setFrame: rect];
    
    // 當MP4完畢播放的回調
    [[NSNotificationCenter defaultCenter]
     addObserver:self selector:@selector(movieFinishedCallback:)
     name:MPMoviePlayerPlaybackDidFinishNotification object:_player];
    
    // 開始播放影片
    [_player play];
    
    // 上層操作層
    _videoOverlayView = [ [LHVideoOverlayView alloc] initWithFrame: rect];
    [keyWindow.rootViewController.view addSubview: _videoOverlayView];
}

2、這種方法是播放結束之後,移除播放view。

- (void)removePlayer:(MPMoviePlayerController*)player
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
    
    [player.view removeFromSuperview];
    [_player release];
    _player = nil;
    
    [_videoOverlayView removeFromSuperview];
    [_videoOverlayView release];
    _videoOverlayView = nil;
}

3、播放完畢,通知外界。

playerPlayFinished 這種方法是空的,沒有通知外界。

我看了下,感覺沒什麽須要。所以沒加。

用法:

1、導入頭文件
#include “LHVideoPlayerImplCpp.h”

2、開始調用接口,如果你要播放的是“loading.mp4”
Size visibleSize = Director::getInstance()->getVisibleSize();
LHVideoPlayerImplCpp::playMP4WithName(“loading”, Rect(0, 0, visibleSize.width, visibleSize.height));
LHVideoPlayerImplCpp::setSkipTitle(“Skip”);

3、影片結束之後,會自己主動移除視圖。

git地址:https://github.com/sunny-liu/Code/tree/master/cocos2dx_3.0_mp4


cocos2d-x 3.0 播放MP4視頻