Firebase Cloud FunctionsとVideo.jsで動画のストリーミング配信に挑戦してみました。
node.jsとExpressでサーバーを作り、htmlファイルを用意し、Video.jsを使いsafari以外のブラウザでHLSを再生できるようにします。
(この記事はざっと書き上げたので、細かい部分説明は追記で書き足していきます。。)
まずExpressは割愛するとして、ともかくNode.jsのRequestモジュールを利用して実装しますのでインストールします。
Requestのインストール
$ npm install --save request
Requestには、HTTP通信を行うために必要で便利なモジュールがたくさん入っています。
Request - Simplified HTTP client
https://www.npmjs.com/package/request#streaming
ここでのストリーミングは、データファイルを断片でロードして、クライアントにちょっとずつ送信していきます。
Cloud Functionの内容
FirebaseでFunctionを作成します。
Functionのコード内容は以下の通り
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const express = require('express');
const request = require('request');
const app = express();
app.get("/embed/v/",function(req,res){
const videopath = '動画ファイルのURL'
request('videopath')
.on('response', (response) => {
console.log(response.statusCode);
})
.on('error', function (err) {
res.sendStatus(404);
console.log(err);
})
.pipe(res);
});
exports.sample = functions.https.onRequest(app);
とてもシンプルでこれだけです。
動画ファイルのURLは、Cloud StorageならそのファイルURLで。
(ルールとか細かい話はここではナシ)
video.jsでHLSを再生できるように
以下のスクリプトが必要なのでインストールします。
<!DOCTYPE html>
<html lang="ja">
<head>
<title></title>
<link href="http://vjs.zencdn.net/7.0/video-js.min.css" rel="stylesheet">
<script src="/js/video.min.js"></script>
<script src="/js/videojs-contrib-media-sources.js"></script>
<script src="/js/videojs-contrib-hls.js"></script>
</head>
<body>
<video id="player" class="video-js" controls preload="none" width="100%" height="100%" poster="http://vjs.zencdn.net/v/oceans.png" data-setup="{}">
<source src="/embed/v/" type="video/mp4">
<p class="vjs-no-js">To view this video please enable JavaScript, and consider upgrading to a web browser that <a href="https://videojs.com/html5-video-support/" target="_blank">supports HTML5 video</a></p>
</video>
<script type="text/javascript">
var player = videojs("player", {
html5: {
hls: { withCredentials: true }
}
});
</script>
</body>
</html>
以上です。
Expressを使っているので、ルーティングパスでファイルIDを取得して、EJSのテンプレート使って動的に動画配信すると良いでしょう。