I wanted to create a site that can play audio using haml, but I could only find HTML articles. I had a hard time writing the code to implement it, so I wrote it as a memorandum.
HTML5 has a tag called audio_tag for playing audio. By using this, you can install a player that can play audio with extensions such as mp3 and wav.
This time I will do it with mp3. The Rails version is 5.2.3.
First, prepare the mp3 sound source you want to play. In my case, the sound source I wanted to use was not mp3, so I changed the extension on this site. https://online-audio-converter.com/ja/
Then create a folder.
app/assets/audios
Put the mp3 sound source in the audios folder. I moved the audio file in the Finder.
This time, I prepared an mp3 called "sample.mp3" as a sample sound source.
Write the code to install the playback player in haml.
.sumple_voice
= audio_tag('sample.mp3', id: 'sample-audio', controls: "controls")
This will install such a player.
The presence of "controls:" controls "" will install the player, and pressing the play button will start playing the specified sound source. There is no problem even if there is no id, so you can delete it if you do not need it.
Now you can play it. However, if this is left as it is, the sound source can be downloaded from the button on the right side of the player where three dots are lined up vertically.
If you are in trouble, you can remove the download button by writing "controls list:" no download "".
.sumple_voice
= audio_tag('sample.mp3', id: 'sample-audio', controls: "controls", controlslist: "nodownload")
Now that the button is gone, I can't download it.
I didn't use it this time because it was aimed at simple audio playback, but it seems that it can be further customized by using audio.js. https://qiita.com/whitia/items/3e533c64ce6b6badfb63 If you want to do various things other than simple playback, you may want to check it out.
https://railsdoc.com/page/audio_tag https://qiita.com/NishidaRyu416/items/c244aeeaacab1d9bb0c1
Recommended Posts