LoginSignup
2
3

実際に使った「ライブ配信サイトでも作ってみない?」2日目

Last updated at Posted at 2023-12-24

まずは簡単なページを作成

stream.html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8" />
        <title>ライブ配信</title>
        <script src="https://cdn.jsdelivr.net/npm/@skyway-sdk/room/dist/skyway_room-latest.js"></script>
        <script src="stream.js"></script>
    </head>
    <body>
        <p>UserID: <span id="my-id"></span></p>
        <div>
            ルームID: <input id="room-name" type="text" />
            <button id="join">配信開始</button>
        </div>
        <video id="local-video" width="400px" muted playsinline></video>
    </body>
</html>

今回はこのようなHTMLを作成しました。
これをベースにいろいろ作っていきます。

初期化

stream.js
const { SkyWayContext, SkyWayRoom, SkyWayStreamFactory, SkyWayAuthToken, uuidV4, nowInSec } = skyway_room;

まずはこれを追加しましょう。
これは、SkyWayにおいて必要なものです。

次に配信に必要な「トークン」を発行しましょう。

const { SkyWayContext, SkyWayRoom, SkyWayStreamFactory, SkyWayAuthToken, uuidV4, nowInSec } = skyway_room;

const token = new SkyWayAuthToken({
  jti: uuidV4(),
  iat: nowInSec(),
  exp: nowInSec() + 60 * 60 * 24,
  scope: {
    app: {
      id: 'ApplicationID',
      turn: true,
      actions: ['read'],
      channels: [
        {
          id: '*',
          name: '*',
          actions: ['write'],
          members: [
            {
              id: '*',
              name: '*',
              actions: ['write'],
              publication: {
                actions: ['write'],
              },
              subscription: {
                actions: ['write'],
              },
            },
          ],
          sfuBots: [
            {
              actions: ['write'],
              forwardings: [
                {
                  actions: ['write'],
                },
              ],
            },
          ],
        },
      ],
    },
  },
}).encode('SecretKEY');

console.log(token);

このようなコードで実行するとトークンが発行されます。
このトークンをコピーしたら、さっきのを置き換えましょう。

const { SkyWayContext, SkyWayRoom, SkyWayStreamFactory, SkyWayAuthToken } = skyway_room;

const token = 'さっきのトークン';

こうして置かないと、ユーザーが自ら権限を持ったトークンを発行することができてしまいます。
※トークンには有効期限の概念があるため、本当はサーバーサイドで発行するべきです。

では次に、初期化関数を作っていきましょう。
これは、アローでもなんでもいいのですが、非同期関数にしておきましょう。

...

const init = async () => {
    const roomIdInput = document.getElementById('room-id');
    const userIdDisplay = document.getElementById('user-id');

    document.getElementById("stream").onclick = async () => {
        if (roomIdInput.value === '') {
            alert('ルームIDを入力してください');
            return;
        }

        const context = await SkyWayContext.Create(token);
    }
}

このようにして早速SkyWayを使い始めてきたinit関数を初期化関数としておきます。
基本的にSkyWayの処理はこの関数の中に書いていきます。

ルームを作成してみよう。

先ほど作成したcontextというのは、SkyWayにおけるグローバルな情報を管理するオブジェクトで、様々なものが管理されています。
このcontextを使用してルームを作成していきます。

document.getElementById("stream").onclick = async () => {
    if (roomIdInput.value === '') {
        alert('ルームIDを入力してください');
        return;
    }

    const context = await SkyWayContext.Create(token);

    const room = await SkyWayRoom.FindOrCreate(context, {
        type: "sfu",
        name: roomIdInput.value,
    });
    const me = await room.join();
    userIdDisplay.innerText = me.id;
}

はいこれだけ。
何とこれだけで、ルームの作成から参加までができちゃいます。

といっても、まだルームに参加しただけで配信などはできていません。

配信ができる環境を作ってみましょう。

配信環境を作ってみよう

const init = async () => {
    const localVideo = document.getElementById('local-video');

    const { audio, video } = await SkyWayStreamFactory.createMicrophoneAudioAndCameraStream();
    video.attach(localVideo);
    await localVideo.play();

    ...

init関数の最初の方にこのようなコードを追加しましょう。

これは、SkyWayのSkyWayStreamFactoryというものを使用して、マイクとカメラのストリームを作成し、映像を表示するというものです。
表示といっても<video>に表示するだけで、配信されているわけではありません。

というわけで早くも配信をしてみましょう。

...次回の記事から!

続く

まずはここまでの段階で、「もうすぐ配信ができそー」なところまで作りました。
次は実際に配信してみましょう。

2
3
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
2
3