Playing an audio file in Grails

Osiyo. Dohiju? Hey welcome back.

With the Cherokee Dictionary Project we’ve wanted to have audio files included so users could hear the words spoken. I also wanted this for listening comprehension on the site for future works. Short story, longer, I read some stackoverflow and didn’t have a good answer, just an ok almost answer.

Here’s what I did:
I am hosting the audio files on my local server so they’ll be pulled locally. This first section is going to cover those files.

In the controller, I’m using to serve audio (specifically mp3s) in this case, I added the following code which most of this answer came from this stackoverflow 6 years ago. It got me most of the way there, but as I said I had to make a change. The big change is using /grailsApplication.mainContext.getResource/ in order to retrieve the file from the server. This is how I load text files to display in some parts of the site now. The rest of the code for the response comes from that stackoverflow post. This code is contained in an audio method in the controller.

File audioFile = grailsApplication.mainContext.getResource("<fileNameHere>.mp3").file

response.setContentLength (audioFile.bytes.length)
response.setHeader("Content-disposition", "attachment;filename=${audioFile.getName()}")
response.outputStream << audioFile.newInputStream() // Performing a binary stream copys
response.setHeader("Accept-Ranges", "bytes");

On the page, I simply do:

<audio type="audio/mp3" src="/<controllerName>/audio?fileName=<pathToMp3>" version="full" controls="">

I won’t leave it like this. the /fileName/ param is the full path right now. However, I will change this so I can either map the audio to a specific name and then lookup the audio. Or I’ll put all of the audio in a specific folder and then only pass in the file name at this point. How I end up doing this will depend on what my end result for the server looks like.

If you want to play audio directly from a server it’s also easy to do. I prefer this path with Grails because you aren’t adding mp3s to your war. You can pull a path from the database, or hardcode it if you want, and play the audio file. The audio files for the ced will be handled in this way. There may be times I want to play audio files hosted inside the webapp directory I now have two options.

<audio type="audio/mp3" src="<pathToMp3>" version="full" controls="">

That’s it.
Until next time. Dodadagohvi.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: