Preview MP3 with HTML5 Audio Element and VueJS

Part 5 of 7 in Your Guide To Uploading Files with VueJS and Axios
Dan Pastori avatar
Dan Pastori October 18th, 2021

The next few tutorials will help build the user experience of your file upload system with Axios and VueJS. This tutorial is specifically focuses on previewing and setting an audio file before allowing the user to upload it. Using this method allows the user to preview what their audio file sounds like before they upload the file to the server to ensure they have the right file.

This tutorial is going to assume you’ve followed along with the series thus far, specifically “Uploading Files With VueJS and Axios“. A lot of the methods are going to look the same and function the same way. We will be building a simple VueJS component that allows the user to select an audio file and preview the file before sending it to the server.

If you want to see a full example, check out our repo. We have full VueJS component examples for you to check out!

Step 1: Limit Files to Audio Only

The first step we need to take is to set our file uploader to accept only audio files:

<input type="file" accept="audio/*" @change="handleFileUpload( $event )"/>

All we have to do is add the accept="audio/*" property to our file input. This will limit the user’s file selector to only audio files.

WARNING: This is great for UX, but you should validate this server side. There are ways you can remove this attribute and send unvalidated data to the server! We want to limit this on the front end, but should be validated on the back end as well!

Step 2: Add Audio Tag

In order to play the audio that you selected to preview, add the following HTML5 audio tag to your VueJS component:

<audio id="audio-preview" controls v-show="file != ''"/>

A couple things to note about the audio tag. First, we have the controls attribute set on the tag. This will display the native browser controls that allow you to control the audio (If you don’t like how this looks, you can always use AmplitudeJS to make the tag and player match your branding 😉).

Second, we gave this the ID of audio-preview. In the next step we will be referencing this tag directly by ID to fill it with the data from the song selected. This can be named whatever you want.

Finally, we are only showing the audio tag if we have a file selected. This is handled through v-show="file != ''". When a file is selected, the audio element will show.

Step 3: Add Preview Audio Method

This is the guts of the process right here. This method will take in the file that we select, read it in, and set it to play through our audio element. To do this, add the following method to your methods:

methods: {
    //...

    previewAudio(){
        let audio = document.getElementById('audio-preview');
        let reader = new FileReader();

        reader.readAsDataURL( this.file );
        reader.addEventListener('load', function(){
            audio.src = reader.result;
        });
    },

    //...
}

Now, when this method is called, we will first grab the audio element by using it’s id audio-preview. This will give us reference to the element so we can work with it.

We also initialize a new FileReader() method. Similar to how we handle image previews, this object will allow us to read in a file and work with the contents.

Also, similar to image previews, we will be calling the readAsDataURL() method and passing in the file that we selected. This will read the audio file as a data URL.

Next, we bind the event listener to the reader for load. When the file is loaded and read, we can work with the contents in the callback. In the callback, we set the result of the reader to audio.src. This is the src attribute on our HTML5 audio element.

With those 6 or so lines of code, we can now preview the audio file selected by the user and give them a chance to play it before they submit it to the server. This leads to a much better UX incase they accidentally select the wrong file.

Step 4: Tying it All Together

There’s only 1 more step. We actually have to call the previewAudio() method. This should happen right after the file is selected, so check out handleFileUpload( event ):

handleFileUpload( event ){
    this.file = event.target.files[0];
    this.previewAudio();
},

Once the user has selected their file, we will run the previewAudio() method so they can listen to what they have selected before uploading.

Conclusion

The previewing of audio files adds a nice bit of UX to the user so they can confirm what they select before uploading it to the server. Next up, we will be doing the same with video files. I’ll give you a quick hint. It’s very similar!

Also, we have our book on SPA and API Driven Development available! If you liked this tutorial and plan on making an app that uses VueJS, check out our book. It goes through a variety of scenarios, tips and tricks using VueJS and APIs. A lot of Axios tips in there as well!

Reach out in the comments section below if you have any questions!

Keep Reading
View the course View the Course Your Guide To Uploading Files with VueJS and Axios
Up Next → Preview Video Before Uploading with HTML5 and VueJS

Support future content

The Ultimate Guide to Building APIs and Single-Page Applications with Laravel + VueJS + Capacitor book cover.

Psst... any earnings that we make off of our book is being reinvested to bringing you more content. If you like what you read, consider getting our book or get sweet perks by becoming a sponsor.

Written By Dan

Dan Pastori avatar Dan Pastori

Builder, creator, and maker. Dan Pastori is a Laravel certified developer with over 10 years experience in full stack development. When you aren't finding Dan exploring new techniques in programming, catch him at the beach or hiking in the National Parks.

Want to learn more about API Driven App Development?

We're writing a book on API Driven App Development. Be the first to know once it is ready!