我在UIWebView
的iOS上尝试以下代码来嵌入YouTube视频:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
body {
margin: 0;
padding: 0;
}
body, html {
height: 100%;
width: 100%;
}
</style>
</head>
<body>
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1" frameborder="0"></iframe>
<script>
var tag = document.createElement('script');
tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady
}
});
}
function onPlayerReady(event) {
event.target.playVideo();
}
</script>
</body>
</html>
我使用以下Swift代码来完成它:
let html = "<!DOCTYPE html><html><head><style type=\"text/css\"> body { margin: 0; padding: 0; } body, html { height: 100%; width: 100%; } </style> </head> <body> <iframe id=\"player\" type=\"text/html\" width=\"100%\" height=\"100%\" src=\"http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1\" frameborder=\"0\"></iframe> <script> var tag = document.createElement('script'); tag.src = \"https://www.youtube.com/iframe_api\"; var firstScriptTag = document.getElementsByTagName('script')[0]; firstScriptTag.parentNode.insertBefore(tag, firstScriptTag); var player; function onYouTubeIframeAPIReady() { player = new YT.Player('player', { events: { 'onReady': onPlayerReady } }); } function onPlayerReady(event) { event.target.playVideo(); } </script> </body></html>"
let width = UIScreen.mainScreen().bounds.width
let height = UIScreen.mainScreen().bounds.height
youTubeWebView = UIWebView(frame: CGRectMake(20, 120, width - 40, height-500))
youTubeWebView.mediaPlaybackRequiresUserAction = false
view.addSubview(youTubeWebView)
youTubeWebView.loadHTMLString(html, baseURL: NSBundle.mainBundle().resourceURL)
但是,虽然视频加载了,但它实际上并不像它应该的那样自动播放。
答案 0 :(得分:1)
尝试放置?rel=0&autoplay=1
<iframe id="player" type="text/html" width="100%" height="100%" src="http://www.youtube.com/embed/M7lc1UVf-VE?rel=0&autoplay=1" frameborder="0"></iframe>
希望能解决你的问题。
BTW:无法在IOS / Mobile中完成
&#34;警告:为了防止用户通过蜂窝网络进行未经请求的下载,嵌入式媒体无法在iOS上的Safari中自动播放 - 用户始终会启动播放。&#34; https://developers.google.com/youtube/iframe_api_reference#Mobile_considerations