A-Frameで動画を埋め込んでみた
こんにちは。A-Frameを使って動画を埋め込んだところ、意外と苦戦するところが多かったのでまとめておきます。
基本的な動画の埋め込み方
A-Frameにはa-videoというタグがあるので、それを使用します。
<a-scene> <a-assets> <video id="bird" autoplay loop="true" src="bird.mp4"></video> </a-assets> <a-video src="#bird" width="16" height="9" position="0 0 -20"></a-video> </a-scene>
スマホ(iPhone)で再生されない問題の解決
必ず書かなければいけない要素
まず、こちらやこちらに書かれているように、必要な要素を付け加えました。
headの中に次のように書きます。
<meta name="apple-mobile-web-app-capable" content="yes">
また、アセットで用意しているa-videoにwebkit-playsinline と playsinlineを加えます。
<a-assets> <video id="bird" muted webkit-playsinline playsinline loop="true" src="assets/videos/bird.mp4"></video>
ここで、autoplayを有効にしているとiPhoneでは絶対に再生されないらしいので消しています。また、音も無いほうがトラブルが少ないようなのでとりあえずmutedにしてあります。
ここまでやって一度試してみましたが依然としてiPhoneでは再生されませんでした。
クリックイベントが必要
さらに続きをよく読むと、iPhoneではユーザーの同意を得るようなアクション(タップなど)が無いと再生されないようです。
ここで前回の記事のようにボタンを作ってみたりしたのですが上手く行かず・・・
最終的に、こちらやこちらを参考にして、動くようになったコードが下記です。
まずはa-sceneに書くhtmlです。
<!-- 再生/停止用のボタン --> <a-entity id="playButton" geometry="primitive: plane; height: 1; width: 1" material="src: #play" position="-7.3 -1.2 0.6" rotation="0 90 0" ></a-entity> <a-entity id="stopButton" click-stop geometry="primitive: plane; height: 1; width: 1" material="src: #stop" position="-7.3 -1.2 -0.67" rotation="0 90 0" ></a-entity>
そしてJavaScriptの部分です。
document.addEventListener("DOMContentLoaded", function(event) { var scene = document.querySelector("a-scene"); var video = document.getElementById("bird"); if (scene.hasLoaded) { run(); } else { scene.addEventListener("loaded", run); } function run () { scene.querySelector("#playButton").addEventListener("click", function(e){ video.play(); }); } }) AFRAME.registerComponent('click-stop', { init: function () { this.el.addEventListener('click', function (event) { document.getElementById("bird").pause(); }); } });
音をON/OFFできるようにする
このままでは無音でしか再生できないので、音のON/OFFボタンを追加しました。
まず、htmlにボタンを追加します。
<a-entity id="musicButton" click-music geometry="primitive: plane; height: 1; width: 1" material="src: #music_off" position="0 -5 -13.26" rotation="0 0 0" ></a-entity>
そしてJavaScriptで制御する部分を書きます。
ちなみに、setAttributeで表示する画像を変更しています。
AFRAME.registerComponent('click-music', { init: function () { this.el.addEventListener('click', function (event) { if(video.muted){ //video.muted = !video.muted; //this also works video.muted = false; this.setAttribute('material', 'src', "#music_on"); }else{ video.muted = true; this.setAttribute('material', 'src', "#music_off"); } }); } });
できたもの
こんな感じ↓になりました。最初は真っ黒ですが再生ボタンを視線クリックすると再生されます。
naughty-agnesi-88cdbc.netlify.app