LoginSignup
9
14

More than 5 years have passed since last update.

Railsでhtml5で追加されたaudioタグを使う

Last updated at Posted at 2017-01-26

前提

まず,assets/audios/任意のファイル
のようなディレクトリ構成にする必要がある。

詳細

<%= audio_tag("audio.mp3",id:"audio") %>
<audio></audio>を生成
一引数にファイル名,二引数にidを指定
調べたところ、mobile環境下では、ボタンを押したら音が流れるというように、ワンクッションおく必要がある。

よって、audio_tagにidを付与し、jsで制御していく
※ここでは、submitボタンが押されたら音がなるようにする。

<%=f.submit "I got it!" ,class:"waves-effect waves-light btn deep-purple darken-2 audioButton"%>

XXX.html.erb
<%=javascript_tag do%>
        document.querySelector('.audioButton').onclick = function () {
        document.querySelector("#audio").play();
        alert("You answered")
        Materialize.toast("You Answered", 4000,'rounded')
        }
<%end%>

まとめ

    <%= audio_tag("audio.mp3",id:"audio") %>
    <%=f.submit "I got it!" ,class:"waves-effect waves-light btn deep-purple darken-2 audioButton"%>
    <%=javascript_tag do%>
        document.querySelector('.audioButton').onclick = function () {
        document.querySelector("#audio").play();
        alert("You answered")
        Materialize.toast("You Answered", 4000,'rounded')
        }
    <%end%>

<%=audio_tag%>の情報はあまりなく、そもそもRailsの基本機能を使って音を流せると知っている方も少ないと思うので、是非お試しください。

9
14
1

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
9
14