0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

スマホ&ブラウザでカメラが使えるか デバイス取得お試し

Posted at

スマホでカメラが使えるか確認
カメラの指定は、コンソールでログ出力して「検証」からデバイス一覧して、配列番号を取得

JS
        const devices = await navigator.mediaDevices.enumerateDevices();
        console.log(devices);

        // カメラからの映像取得   //私のスマホの背面カメラは1番
        const stream = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: { deviceId: devices[1].deviceId },

index.html
<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Camera Test</title>
  </head>

  <body>
    <h1>Webカメラテスト</h1>

    <video id="myvideo" width="640" height="480" muted autoplay playsinline></video>

    <script>

      // 関数の定義
      async function main() {
        // デバイス(カメラ・マイク)からのデータ取得を試みる
        // 映像や音声が使えるデバイスが確定するまで時間がかかるためawaitを使う
        const devices = await navigator.mediaDevices.enumerateDevices();
        console.log(devices);

        // カメラからの映像取得   //私のスマホの背面カメラは1番
        const stream = await navigator.mediaDevices.getUserMedia({
        audio: true,
        video: { deviceId: devices[1].deviceId },
        });
        // IDが"myvideo"であるDOMを取得
        const video = document.getElementById('myvideo');
        // myvideoなvideo要素のsrcObject(映像オブジェクトを入れるところ)にデータ(メディアストリーム)をセットする
        video.srcObject = stream;
      }

      // 実行する
      main();

    </script>
  </body>
</html>
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?