How to play audio and music using javascript

Preface

I am a beginner for 3 months since I started learning programming by myself. As I continued to study while hitting the wall many times, I was helped by the articles of the pioneers. I decided to post an article in the hope that it would help those who are worried.

This article is based on the content that I investigated from the desire to play audio at the time of Javascript (hereinafter abbreviated as JS) event or when performing specific processing in the process of creating a web application. I will. Originally, HTML has an audio element, and you can play audio by specifying the location of the file in the src attribute of the audio element. However, under Rails environment, specifying the file location did not work, and as a result of stumbling, I decided to use a gem called "audiojs-rails".

Purpose#

In this article, I will describe it for the purpose of "Hiding the playback player and playing the sound when the HTML Input button is pressed". If you arrange it, it will be possible to play it after a specific process is completed.

usage environment#

OS:Win10 Rails 5.2.4.4 Ruby 2.6.6 Currently under development in a local environment

table of contents#

◆ How to install and use Gem ◆ Arranged so that it can be played by a specific event ◆ Hide the playback player!

◆ How to install and use Gem to use

1. 1. Add the following contents to the Gemfile and perform bundle install.
gem 'audiojs-rails'
2. Initialization of audiojs and installation of playback player

Describe the following contents in the View where you want to play the audio data. A playback player is created by audiojs.createAll ().

<!--Play player-->
<%= audio_tag 'sample.mp3' %>

<!--initialization of audiojs-->
<script>
    const audioPlayer = audiojs.createAll();
</script>
3. 3. Add assets path

"Sample.mp3" loaded by the playback player installed above is the name of the audio file. You can prepare your favorite file, but be careful about the storage location. Be sure to place it in app / assets / audios /. (I created it because I didn't have the audios folder, but it worked fine.)

However, it cannot be used just by saving it, so add an assets path for delivery in the asset pipeline. Add the following to config / initializers / assets.rb.

config/initializers/assets.rb


Rails.application.config.assets.paths << Rails.root.join("app", "assets", "audios")
4. Check if the assets path has been added.

At the command line you are using, launch the Rails console and type in the following:

Rails.application.config.assets.paths

As a result, if the folder path with audios at the end is read, there seems to be no problem.

"C:/Users/sample/ruby/webapp/app/assets/audios"

After confirming that the path has been added, let's see if it can be played. If you can play it, you are ready to go.

◆ Arrange so that it can be played by a specific event.

1. Add Input tag to View, set ID, and read it with Script.

This time, I assign an ID called operation to a variable.

python



<input type="submit" id="operation">
<script>
    const operation = document.getElementById("operation");
    const audioPlayer = audiojs.createAll();
</script>
2. Playback Plays audio when the player information is assigned to the audio variable and input is clicked.

python



<input type="submit" id="operation">
<script>
    const operation = document.getElementById("operation");
    const audioPlayer = audiojs.createAll();
#Contents added from here
    const audio = audioPlayer[0];

    operation.addEventListener("click", () => {
        audio.play();
    });
#So far
</script>

I don't understand exactly why you have to put audioPlayer [0] for audio, When I looked into the contents of audioPlayer on Console.log, I found that it was as follows. キャプチャ.PNG The information when the playback player was generated is stored in audioPlayer. Therefore, since the content of index number 0 contains audio file information and information related to operations such as play and stop, it is speculated that it may not work unless it is specified.

◆ Hide the playback player!

All you have to do is enclose the Audio_tag in a Div tag and set the CSS Display to none.

<div class="none">
    <%= audio_tag 'decision48.mp3' %>
</div>    

Finally

This time I tried to summarize the contents of manipulating the information of various articles in my own way. If you have any questions, please let us know. I will also summarize the articles that I referred to, so if you are interested, please do!

[Rails] Procedure from installation of audiojs-rails to playback of audio files ↑ Playback player options are also summarized. If you want to play with the playback player, please come. ・ Note of javascript (audio.js) to play MP3 ↑ I am making a play button and a stop button using jQuery. If you apply it, you may be able to do the same with JS alone.

Recommended Posts

How to play audio and music using javascript
How to output Excel and PDF using Excella
How to execute and mock methods using JUnit
[Swift] How to play songs from your music library
How to convert A to a and a to A using AND and OR in Java
How to use Play Framework without using typesafe activator
How to authorize using graphql-ruby
How to test including images when using ActiveStorage and Faker
Difference between Java and JavaScript (how to find the average)
How to set and describe environment variables using Rails zsh
How to join a table without using DBFlute and sql
How to play MIDI files using the Java Sound API
How to use StringBurrer and Arrays.toString.
How to use EventBus3 and ThreadMode
How to call classes and methods
How to use equality and equality (how to use equals)
How to connect Heroku and Sequel
How to convert LocalDate and Timestamp
java Eclipse How to debug javaScript
How to build CloudStack using Docker
How to POST JSON in Java-Method using OkHttp3 and method using HttpUrlConnection-
[Rails] How to upload images to AWS S3 using Carrierwave and fog-aws
[Rails] How to upload images to AWS S3 using refile and refile-s3
How to execute a contract using web3j
How to use OrientJS and OrientDB together
[Android] How to turn the Notification panel on and off using StatusBarManager
How to install Play Framework 2.6 for Mac
How to deploy to AWS using NUXTJS official S3 and CloudFront? With docker-compose
[Rails] How to upload images using Carrierwave
How to realize hybrid search using morphological analysis and Ngram with Solr
How to use BootStrap with Play Framework
[Android] How to pass images and receive callbacks when sharing using ShareCompat
[Java] How to output and write files!
How to set up and use kapt
How to build SquashTM and how to support Japanese
How to find the tens and ones
[Easy] How to upgrade Ruby and bundler
[Swift5] How to implement animation using "lottie-ios"
How to use substring and substr methods
How to implement image posting using rails
How to make asynchronous pagenations using Kaminari
Note: [Docker] How to start and stop
How to write and explain Dockerfile, docker-compose
[Rails] How to handle data using enum
How to use @Builder and @NoArgsConstructor together
How to insert icons using Font awesome
How to play MIDI files using the Java Sound API (specify the MIDI device to use)
Differences between Java, C # and JavaScript (how to determine the degree of obesity)
[Ruby] How to calculate the total amount using the initialize method and class variables
JDBC promises and examples of how to write
[Ruby] How to convert from lowercase to uppercase and from uppercase to lowercase
[Java] How to use FileReader class and BufferedReader class
[Rails] How to create a graph using lazy_high_charts
[Java] How to get and output standard input
[Ruby] How to use gsub method and sub method
How to delete a controller etc. using a command
[Ethereum] How to execute a contract using web3j-Part 2-
How to implement the breadcrumb function using gretel
How to use Segmented Control and points to note
Git and GitHub ~ How to fix common errors ~
How to set up and operate jEnv (Mac)