Help us understand the problem. What is going on with this article?

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.

https://stackoverflow.com/questions/49930680/how-to-handle-uncaught-in-promise-domexception-play-failed-because-the-use

jin-jar-ale
プログラマ | 広告代理店、フィンテック、スタートアップ、Eコマース、オークションでソフトウェアエンジニアやってました | 情報工学系修士 | 個人アカウントのため、所属する組織とは関係ありません
brainport
ブレインポートは、システム受託開発、中小企業向けIT支援サービスや自社サービス、ソフトウェアなどを展開するスタートアップ企業です。
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした