---
layout: post
title: HTML5 Audio Tag
date: 2015-09-25 13:33:00 +0000
summary: Using the HTML5 Audio Tag to Get Metadata From a MP3 on the Client
---

I just recently had the experience of building a podcast manager. One of the challenges I faced was being able to extract metadata from the audio files that I was given. The problem lays in the way I had the project setup for deployment. Which is to have a server running on [Heroku](http://heroku.com) using the [Laravel](http://laravel.com) framework then all the audio files were to be uploaded directly from the client to Google Cloud Storage(GCS). As Heroku doesn't allow you to write to the hard drive and all of the PHP libraries I came across that were going to read the metadata from the files was done by reading from the hard drive instead of memory. So I had to come up with a way to read the files I was given before uploading them to GCS.

In order to be able to load the files the user has selected to upload you first need to create an in memory url to the file via `URL.createObjectURL(file)`. The `file` variable being an instance of `File`. You then pass the generated URL into a src attribute of an `audio` tag. Once the file has been loaded into the audio after the `canplaythrough` event is emitted you can extract the metadata by getting access to the DOM element itself. You can now use any of the following [properties](http://www.w3schools.com/tags/ref_av_dom.asp) to get data about the audio file. So for example you can get the duration like so:

```javascript
var audio = document.querySelector('audio');
audio.addEventListener('canplaythrough', function () {
  var duration = audio.duration;
});
```

After you have gotten the necessary metadata you need to free the browser's memory of the URL you generated earlier by using `URL.revokeObjectURL(url);`. If you don't do this, your page will become very slow and sluggish because the file is being temporarily stored in the browser's memory.

Once I had gotten the data I needed, I then proceeded to upload the file to GCS and send an AJAX request to my server with the data I had gotten.

Write first blog podcast. Yay!
Write first blog podcast. Yay!
