gpt4 book ai didi

ios - 如何在 WKWebView 中自动播放 youtube 视频?

转载 作者:行者123 更新时间:2023-12-01 15:57:43 30 4
gpt4 key购买 nike

我编写了一个代码来在 WKWebView 中播放 youtube 视频。我想在加载屏幕时自动播放视频,内联视频也不应该在新屏幕中播放。下面是我的代码。

 @IBOutlet weak var myPlayer: WKWebView!
override func viewDidLoad() {
super.viewDidLoad()

if let videoURL:URL = URL(string:
"https://www.youtube.com/embed/695PN9xaEhs?playsinline=1") {
let request:URLRequest = URLRequest(url: videoURL)
myPlayer.load(request)
}
}

我已经在界面构建器中为 WKWebView 设置了配置。

Interface Builder Attribute Properties

enter image description here

任何人都可以提供在 View 加载时自动播放的建议吗?

最佳答案

使用 iFrame 在 WKWebview 上加载视频并编写脚本以自动播放视频。请参阅以下代码。

class YouTubeVideoPlayerVC: UIViewController {

@IBOutlet weak var videoPlayerView: WKWebView!
var videoURL:URL! // has the form "https://www.youtube.com/embed/videoID"
var didLoadVideo = false

override func viewDidLoad() {
super.viewDidLoad()
videoPlayerView.configuration.mediaTypesRequiringUserActionForPlayback = []
}

override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
// Size of the webView is used to size the YT player frame in the JS code
// and the size of the webView is only known in `viewDidLayoutSubviews`,
// however, this function is called again once the HTML is loaded, so need
// to store a bool indicating whether the HTML has already been loaded once
if !didLoadVideo {
videoPlayerView.loadHTMLString(embedVideoHtml, baseURL: nil)
didLoadVideo = true
}
}

var embedVideoHtml:String {
return """
<!DOCTYPE html>
<html>
<body>
<!-- 1. The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

<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', {
playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 },
height: '\(videoPlayerView.frame.height)',
width: '\(videoPlayerView.frame.width)',
videoId: '\(videoURL.lastPathComponent)',
events: {
'onReady': onPlayerReady
}
});
}

function onPlayerReady(event) {
event.target.playVideo();
}
</script>
</body>
</html>
"""
}
}

查看以下帖子了解更多信息 Autoplay YouTube videos in WKWebView with iOS 11

关于ios - 如何在 WKWebView 中自动播放 youtube 视频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55626173/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com