我正在尝试使用YTplayer自动播放youtube的视频并使用VideoID加载Youtube视频, 我也尝试在Webview中使用loadHTMLString。 iOS不允许自动播放youtube吗?
这是我的代码:1)使用YTplayer
let fullNameArr = video_url!.componentsSeparatedByString("=")
let video: String = fullNameArr[1]
enYTplayer.webView?.mediaPlaybackRequiresUserAction = false
YTplayer.webView?.allowsInlineMediaPlayback = true
YTplayer.loadWithVideoId(video)
YTplayer.playVideo()
2)使用webView(iframe)
let vidurl = "https://www.youtube.com/embed/LG-_Dz6nseQ"
yutub_webview.loadHTMLString("<iframe width=\"\(yutub_webview.frame.size.width)\" hight=\"\(yutub_webview.frame.size.height)\" src=\"\(vidurl)?playsinline=1\" frameborder=\"0\" allowfullscreen & autoplay=1 &showinfo=0 &controls=0 autohide=1></iframe>", baseURL: nil)
3)使用HTML
let youTubeVideoHTML :NSString = "<html><head><style>body{margin:0px 0px 0px 0px;}</style></head> <body> <div id=\"player\"></div> <script> var tag = document.createElement('script'); tag.src = 'http://www.youtube.com/player_api'; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubePlayerAPIReady() { player = new YT.Player('player', { width:'200', height:'204', videoId:'8LVN7WVgx0c', events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body> </html>";
yutub_webview.loadHTMLString(youTubeVideoHTML as String,baseURL:nil)
并尝试了这个:
yutub_webview.loadHTMLString("<html><body style='margin:0px;padding:0px;'><script type='text/javascript' src='http://www.youtube.com/iframe_api'></script><script type='text/javascript'>function onYouTubeIframeAPIReady(){ytplayer=new YT.Player('playerId',{events:{onReady:onPlayerReady}})}function onPlayerReady(a){a.target.playVideo();}</script><iframe id='playerId' type='text/html' width='300' height='200' src='http://www.youtube.com/embed/LG-_Dz6nseQ? enablejsapi=1&rel=0&playsinline=1&autoplay=1' frameborder='0'></body></html>",baseURL: NSBundle.mainBundle().bundleURL)
但仍然默认播放按钮,视频不自动播放。 任何人都可以告诉我这些错误吗?
答案 0 :(得分:2)
只需添加YTPlayerViewDelegate的委托
并使用其方法 -
func playerViewDidBecomeReady(playerView: YTPlayerView) {
YTplayer.playVideo()
}