Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
6
Help us understand the problem. What is going on with this article?

More than 1 year has passed since last update.

@jin-jar-ale

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

実行環境

  • 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('音が鳴ったよ'));
}

気になったこと

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

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

6
Help us understand the problem. What is going on with this article?
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
6
Help us understand the problem. What is going on with this article?