如何在WKWebView中自动播放YouTube视频?

9

我已经编写了一段代码,在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

有人能提供一个建议,让视图加载时自动播放吗?


3
可能是 Autoplay YouTube videos in WKWebView with iOS 11 的重复问题。 - Kamran
这也可能是一个重复的问题 - https://dev59.com/SWUo5IYBdhLWcg3w3ycF - AjinkyaSharma
是的,但我想要内联播放和自动播放。 - Manish
我已经为此提出了标志。谢谢。 - Manish
3个回答

7

在创建web视图时,请确保传递配置。像这样:

let configuration = WKWebViewConfiguration()
configuration.allowsInlineMediaPlayback = true
configuration.mediaTypesRequiringUserActionForPlayback = []
let webView = WKWebView(frame: .zero, configuration: configuration)

1
这个配置和在类似于 https://www.youtube.com/embed/RRxQQxiM7AA?autoplay=1 的URL中的自动播放功能不起作用。有人可以确认这对他们有效吗? - Garvan Keeley

7

使用 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>
        """
    }
} 

欲了解更多信息,请参见以下帖子:IOS 11中使用WKWebView自动播放YouTube视频


谢谢Atul,它是有效的,但有一个问题,我想内联播放。我们怎么做? - Manish
我已经将 allowsInlineMediaPlayback 设置为 true,但是没有生效。 - Manish
1
Atul发现了解决方案,我们需要在player中添加参数function onYouTubeIframeAPIReady() { player = new YT.Player('player', { playerVars: { 'autoplay': 1, 'controls': 0, 'playsinline': 1 }, height: '\(myPlayer.frame.height)', width: '\(myPlayer.frame.width)', videoId: '\(videoURL.lastPathComponent)', events: { 'onReady': onPlayerReady } }); } - Manish
好的,非常感谢您提供的解决方案,我已经更新了我的答案,请接受这个答案,谢谢。 - AtulParmar

-2

需要用户操作才能播放的媒体类型

//Determines which media types require a user gesture to begin playing.
var mediaTypesRequiringUserActionForPlayback: WKAudiovisualMediaTypes

只需将此属性设置为空数组即可自动播放。


兄弟,我以前试过这个,不知道为什么它不起作用。 - Manish

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接