Sign in

Recording, Persisting, and Appending Audio In a Rails/JS App

The Broad Strokes

Before going into the nitty-gritty, let’s make sure we have a good overall game plan. The first step is to get permission to access the user’s mic and then record audio through the frontend. Next, we have to package and send that data to the backend where it will be associated with a ruby object and persisted in the database. After that, we have to call upon that data to make a JS object in the frontend, and ultimately append it to the page in a user friendly way. This article assumes the knowledge to do all of the above with a simpler data type, such as text.

Step 1: Getting mic access

To gain access to a user’s mic, we need to ask permission.

  1. The code after the first ‘then.’ creates a new MediaRecorder instance once the getUserMedia call has been completed successfully.
  2. The code after the second ‘then’ is run if the getUserMedia call fails for whatever reason.

Step 2: Setting up the starting HTML

First add an <article> tag to the HTML so that we have somewhere to put the audio players once we append them. Then create a record/stop button on that same index.html (Don’t forget to give both of these elements some id so we can reference it later). We will link this button to a click event that will start recording. Do this inside the “DOMContentLoaded” event listener which should now look like this:

Step 3: The start function

As you can see above, the recording button that exists on the page from the start is linked to a function called ‘start’ that will be in the same file. The ‘start’ function will do four things: Declare a blank array to capture our audio data, start our already instantiated MediaRecorder instance, push the data into the array as it becomes available and set up what happens when we click the ‘stop’ button.

Step 4: Package and send audio to backend with a fetch POST request

Step 5: Set up ActiveStorage and Persist Audio

To properly set up ActiveStorage, follow the same procedure as the first section here, but instead of photos we are doing audio.

Step 6: Call upon data and create a JS object

The data will be send back to the frontend using json. The picture in step 4 is relevant here again. We are pretty much looking at everything from .then onwards.

Step 7: Append to page in and <audio> tag

This was the part I thought would be the hardest. Turns out it’s the easiest! All you have to do is create an audio element, set the controls: