DEV Community

codemee
codemee

Posted on

4 2

iOS 上使用 getUserMedia() 取用相機但畫面鎖死、黑屏

tags: FM611A FM628A iOS webcam

Media Streaming API 可以在使用者自己同意的前提下在網頁應用程式中取用裝置上的相機或是麥克風, 以下是使用相機的基本網頁程式:

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <title>getUserMedia test</title>
</head>

<body>
    <video id="video" autoplay="true"></video>
    <script>
        var video = document.querySelector("#video");

        if ((navigator.mediaDevices && navigator.mediaDevices.getUserMedia)) {
            navigator.mediaDevices.getUserMedia({
                video: true,
                audio: false
            })
            .then(function (stream) {
                video.srcObject = stream;
                video.play();
            })
            .catch(function (err) {
                console.log("你拒絕使用相機:" + err);
            });
        } else {
            console.log("您的瀏覽器不支援影像功能");
        }
    </script>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

要注意的是相機與麥克風涉及隱私, 因此 Media Streaming API 只能在本機檔案或是透過 https 加密協定取得的網頁內運作, 如果在 http 未加密協定取得的網頁內, navigator.mediaDevices 會是 undefined, 就無法叫用 getUserMedia() 取用相機了。

以上的示範網頁雖然可以正常運作, 不過在 iOS 上卻會遇到相機畫面鎖死, 完全不會更新:

或者是黑屏的狀況, 像是這樣:

根據網路上查到的解決方案, 這似乎是 webkit 的臭蟲, 解決方法很莫名其妙, 就是在 <video> 標籤加上 playsinline 屬性就可以了, 像是這樣:

<!DOCTYPE html>
<html>
...
<body>
    <video id="video" autoplay="true" playsinline></video>
...
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

你就可以在網頁中正常使用相機了:

這個問題到目前為止仍然存在 iOS 中, 不知道的話就會被雷到。

你可以在這裡測試加或是不加 playsinline 屬性的網頁:

Sentry mobile image

Mobile Vitals: A first step to Faster Apps

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read the guide

Top comments (0)

Sentry mobile image

App store rankings love fast apps - mobile vitals can help you get there

Slow startup times, UI hangs, and frozen frames frustrate users—but they’re also fixable. Mobile Vitals help you measure and understand these performance issues so you can optimize your app’s speed and responsiveness. Learn how to use them to reduce friction and improve user experience.

Read full post →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay