Play HTML5 audio in the browser

This article first appeared in the May issue (227) of .net magazine – the world's best-selling magazine for web designers and developers.

Traditionally, anything audio-based on the web has played sound as a Flash applet. Now HTML5 is set to take over, and with Adobe stopping development of Flash for mobile, many Flash developers are looking for new ways to do the things they used to in HTML5.
HTML5 is great, but audio is one of the areas that’s still a work in progress. So, how does one play audio in HTML5? There are several options. One is the <audio> tag, supported by all major browsers. You can call this from JavaScript as easily as new Audio('music.ogg').play(). But it’s designed for streaming music, and some browsers have issues with playback when it’s used heavily for things such as game sound effects. Here are a few more useful methods:

var a = new Audio(‘sound.ogg’); – create new audio; – start playing
a.pause(); – stop playing
a.currentTime = 0; – rewind to beginning
a.duration; – returns length
a.ended; – returns true if finished
a.loop = true; – set looping
a.volume = 0.5; – half volume
a.muted = true; – mute
a.addEventListener('ended', func); – call ‘func()’ when finishes playing

Thank you for reading 5 articles this month* Join now for unlimited access

Enjoy your first month for just £1 / $1 / €1

*Read 5 free articles per month without a subscription

Join now for unlimited access

Try first month for just £1 / $1 / €1

The Creative Bloq team is made up of a group of design fans, and has changed and evolved since Creative Bloq began back in 2012. The current website team consists of eight full-time members of staff: Editor Georgia Coggan, Deputy Editor Rosie Hilder, Ecommerce Editor Beren Neale, Senior News Editor Daniel Piper, Editor, Digital Art and 3D Ian Dean, Tech Reviews Editor Erlingur Einarsson and Ecommerce Writer Beth Nicholls and Staff Writer Natalie Fear, as well as a roster of freelancers from around the world. The 3D World and ImagineFX magazine teams also pitch in, ensuring that content from 3D World and ImagineFX is represented on Creative Bloq.