iOS UIWebView video auto play

iOS使用WebView來作為MediaPlayer相當的方便,不但可以播放Youtube,也可以播放local的影音檔案,但在iOS使用html5的autoplay 功能卻會無法正常使用必須在Native(objective-c)這端加上這段
[webView setMediaPlaybackRequiresUserAction:NO];

而html這邊設定自動播放方式如下:
<video src="YOURFILEPATH" autoplay ></video>

光是使用video tag來播放還是會遇上些播放狀態的問題,由於autoplay會直接進行全螢幕播放,在Native SDK可以取得進入全螢幕、離開全螢幕事件,只要放在Init webview之後,使用Notification Center方式來傳送訊號
//進入全螢幕
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeStarted:) name:@"UIMoviePlayerControllerDidEnterFullscreenNotification" object:nil];
//離開全螢幕
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(youTubeFinished:) name:@"UIMoviePlayerControllerDidExitFullscreenNotification" object:nil];

而取得這些Notification的function如下
-(void)youTubeStarted:(NSNotification *)notification{
// your code here
NSLog(@"ENTER!!!");
}

-(void)youTubeFinished:(NSNotification *)notification{
// your code here
NSLog(@"EXIT!!!!!");
}


如果有需要使用javascript來控制影片的播放,如暫停、播放、播放完畢、目前播放秒數...等資訊也是相當簡單,以下為使用jQuery為例
//播放完畢
$("video").bind("ended", function() {
//end
});

//暫停
$('video').bind("pause",function(e){
//pause
});

//播放
$('video').bind("play",function(e){
//play
});

//目前播放時間(秒)
$('video').bind("timeupdate",function(e){
//timeupdate
});


其中播放完畢後預設為停在結束畫面並不會自動關閉播放模式,必須使用下面這行來進行離開全螢幕播放模式
$('video').get(0).webkitExitFullScreen();


如果要使用Javascript取得目前是否全螢幕瀏覽可使用下面方式判斷,回復為true為全螢幕,若為false為離開全螢幕
$('video').get(0).webkitDisplayingFullscreen;


相關連結
Opera Dev - Introduction to HTML5 video
iOS Developer Library
iOS Developer Library - WebView

沒有留言:

張貼留言