Tuesday 30 April 2019

How to play audio in WKWebView?

I'm making an iOS app to wrap my javascript game and audio plays fine on mobile safari, but not when in my native app's webView. I want to play audio with javascript audio.play()

In the javascript on audio.play() I get NotSupportedError: The operation is not supported. myAudio.readyState is 0. canplaythrough never happens.

<html>
    <body>
        <div id=debug style='font-size:20px' onclick="playSound(myAudio)">
            Debug<br />
            Tap here to play the sound2.<br />
        </div>
        <script>
            var url = "http://curtastic.com/gold.wav"
            //var url = "upgrade.wav" // I have also tried local audio files within the project. Same error.
            var myAudio
            var context = new webkitAudioContext()
            var playSound = function(sound)
            {
                log("playSound() readyState="+sound.readyState)
                sound.play()
                //Someone said to try it this way. Same error.
                context.resume().then(() => {
                                      log("Context resumed")
                                      sound.play()
                                      })
            }

            var myAudio = new Audio(url)
            myAudio.addEventListener('canplaythrough', function(){log('canplaythrough')}, false)

            function log(m)
            {
                console.log(m)
                debug.innerHTML += m+"<br />"
            }
        </script>
    </body>
</html>

And ViewController.swift

import UIKit
import WebKit

class ViewController: UIViewController {
    private var myWebView3 : WKWebView!
    override func viewDidLoad() {
        super.viewDidLoad()

        self.myWebView3 = WKWebView(frame: .zero)

        self.myWebView3.configuration.preferences.setValue(true, forKey: "allowFileAccessFromFileURLs")
        self.myWebView3.configuration.mediaTypesRequiringUserActionForPlayback = []
        self.myWebView3.configuration.allowsInlineMediaPlayback = true

        let url = Bundle.main.url(forResource: "index6", withExtension: "html", subdirectory: "/")!
        self.myWebView3.loadFileURL(url, allowingReadAccessTo: url)
        let request = URLRequest(url: url)
        self.myWebView3.load(request)

        self.view.addSubview(self.myWebView3)
    }

    override func viewDidLayoutSubviews() {
        self.myWebView3.frame = self.view.bounds
    }

}

I'm using Xcode 10.1 iPhone SE 12.1.1 I have also tried on an iPad with iOS 10 and get the same error. I have also tried playing the sound inside ontouchstart and get the same error. I have also tried context.decodeAudioData() / context.createBufferSource() and get the same error.



from How to play audio in WKWebView?

No comments:

Post a Comment