4
7

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.

webpackerでmp3を使う場合 (audio_tag) Railsで音を鳴らす方法

Last updated at Posted at 2020-01-08

実行環境

  • macOS
  • Ruby 2.6.5
  • Rails 6.0.1
  • ts 3.7.3
    • es2019

使う場合

  • app/assets/audios にmp3ファイルを置く
  • webpackerの設定ファイルを変更する

サンプルコード

  • app/assets/audios/test.mp3 を配置
config/webpacker.yml
  static_assets_extensions:
    # 以下の項目を追記する
    - .mp3

webpackerをdevelopment環境で使う場合に拡張子を追加しておく

app/assets/config/manifest.js
//= link_tree ../audios

audiosファイルをmanifestにつなげる

app/views/top/index.html.haml
= audio_tag('test.mp3', id: 'test-audio')
app/javascript/packs/test.ts
const audio = document.getElementById('test-audio');
if (audio !== null) {
  (<HTMLMediaElement>audio).play().then(() => alert('音が鳴ったよ'));
}

気になったこと

以下のエラーが発生する時があるらしい

.js
Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.

4
7
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
4
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?