Skip to content
View in the app

A better way to browse. Learn more.

Web Designer Forum

A full-screen app on your home screen with push notifications, badges and more.

To install this app on iOS and iPadOS
  1. Tap the Share icon in Safari
  2. Scroll the menu and tap Add to Home Screen.
  3. Tap Add in the top-right corner.
To install this app on Android
  1. Tap the 3-dot menu (⋮) in the top-right corner of the browser.
  2. Tap Add to Home screen or Install app.
  3. Confirm by tapping Install.

Featured Replies

I've created this lightweight mp3 player from scratch using an audio element and raw JavaScript for the controls. Besides for the lack of support for native mp3 in most Firefox versions it seams to work fine in all modern browsers. I'm using DOM 2-style EventListeners instead of onclick, onload ect. which is very new to me. For that reason I would appreciate if anyone feels like talking a look at the code and post suggestions for improvement here.

 

I've created a jsfiddle here: http://jsfiddle.net/Nillervision/s72b2/

 

If you wish to use the player in your own projects feel free to copy the source from here (HTML with css and js embedded).

It's very easy to use.

To add items to the playlist simply add a link to an mp3 file in the ordered list.

The css works with responsive designs.

 

EDIT: Sorry for the double post. After submitting i landed on an error page, refreshed the page and must have submitted again by accident

Edited by Nillervision

  • Author

I've just updated the code. I realized I was attaching events to all a tags in the entire document:

//Ataching events
function registerEvents() {
	stopPlayback();
	var tracks = document.getElementsByTagName('a');
	for (var i = 0; i < tracks.length; i++) {
		tracks[i].addEventListener('click', playTrack, false)
	}
	btnStop.addEventListener('click',stopPlayback,false);
	audio.addEventListener('ended', stopPlayback,false);
}

I've changed it to this:

//Ataching events
function registerEvents() {
    stopPlayback();
    var tracks = document.getElementById('trackList').children;
    for (var i = 0; i < tracks.length; i++) {
        tracks[i].addEventListener('click', playTrack, false)
    }
    btnStop.addEventListener('click',stopPlayback,false);
    audio.addEventListener('ended', stopPlayback,false);
}

The links in my original post now points to the updated code

Edited by Nillervision

  • Author

And yet another update

I've attempted to add a support check using the canPlayType type. This wierd method is not returning boolean values as you might think but 3 possible strange values:

  1. "probably" - the browser most likely supports this audio/video type
  2. "maybe" - the browser might support this audio/video type
  3. "" - (empty string) the browser does not support this audio/video type

For now I have just added an error message if the method returns an empty string...

 

//Check for browser support, initialise and attach eventlisteners
function registerEvents() {
    if (audio.canPlayType('audio/mpeg')==""){
        messages.innerHTML="Sorry! your browser does not seam to support HTML5/mp3 audio";
    }
    else{
        stopPlayback();
        var tracks = document.getElementById('trackList').children;
        for (var i = 0; i < tracks.length; i++) {
            tracks[i].addEventListener('click', playTrack, false)
        }
        btnStop.addEventListener('click',stopPlayback,false);
        audio.addEventListener('ended', stopPlayback,false);
    }
}

Hope it's OK with everyone that I continue this lonely thread. I'm still hoping for some inputs from all you javascript ninjas out there :)

Edited by Nillervision

  • 1 month later...
  • Author

Finaly I found time to finish my Audio Player. It now have the following features:

  • Native html5 and raw Javascript (no plug-ins or frameworks needed)
  • No JavaScript knowledge needed to use the player
  • Custom HTML Playlist (just ad normal html links to mp3 files)
  • Volume -and progress sliders (only visible when playing a track)
  • Responsive layout.

 

Try it and grab the source (single html file) from here:

http://www.nielsharbo.dk/test/audioplayer/audioplayer.html

 

If you'd like to play around with the code online theres a jsfiddle here:

http://jsfiddle.net/Nillervision/s72b2/

 

The look of the player could be better, so if anyone feels like making a theme with some nice icons please let me know.

Edited by Nillervision

Brilliant!

 

I've just played it without looking hard at the code, but I will study it.

 

I agree that the look is a bit bland; it needs skin options , perhaps one very simple in grey and blues so it fits in with any web page and another with bright colours to be more exciting.

  • Author

Looks good. What about adding Ogg and Wav support?

Damn just when I thourght the wok was done. :bangb: Good point Jack. I chose to start with mp3 as it's the only format that is supported in all browsers now and simply forgot to get back to the other file types. But it should be quite easy to get the file extention from the href and set the type attribute to match. So I will definitely need to work on that next. The harder part will be to figure out how to fall back from one type to another. But I will give me something to do in those long cold winter nights.

 

To make it work in all browsers - use <source> elements inside the <audio> element. <source> elements can link to different audio files. The browser will use the first recognized format:
<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>

http://www.w3schools.com/tags/att_audio_src.asp

  • Author

Yes it is (finaly) at least on Windows and Linux. Mozilla have now added support for mp3 I don't know about Mac though.

 

 

EDIT: Sorry didn't see the "on mac yet" part

Edited by Nillervision

  • Author

 

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">
  Your browser does not support the audio tag.
</audio>

http://www.w3schools.com/tags/att_audio_src.asp

Thanks DigitalSoulArts. but I have to figure out how to enable the fallback for users as the source and type attributes is getting set dynamically by looping through the links. (I want to use links as it will allow users without support to download or play with a plugin) I guess I'll just have to add a few more conditional statements.

  • Author

UPDATE - OGG SUPPORT:

Now I have added an optional .ogg fallback. The publisher/blogger/editor can choose to give the links an data attribute with an ogg-file like this:

<a href="audiofile.mp3" data-oggfallback="audiofile.ogg">My cool audio</a>

The play-function in the JavaScript first checks if the browser supports mp3 and assign the correct attributes in that case. If not the script will check if ogg is suported AND IF A DATA ATTRIBUTE HAS BEEN SET

 

if(audio.canPlayType("audio/mp3")){
            audio.setAttribute('src', this.href);
            audio.setAttribute('type', 'audio/mpeg');
}
else if(audio.canPlayType("audio/ogg")&& this.hasAttribute("data")){
            audio.setAttribute('src', this.data('oggfallback'));
            audio.setAttribute('type', 'audio/ogg');
}
else{
        messages.innerHTML='Your browser does not support playback of these files';
}

Everything should be working correctly in any major browser that supports HTML 5.

Mac users please test and report any issues. I have only tested on a windows machine with native mp3 support in all browsers.

 

You can try it here (and grab the source if you want to use it in you own html pages)

http://www.nielsharbo.dk/test/audioplayer/audioplayer.html

 

Here's a jsfiddle if you prefer that:

http://jsfiddle.net/Nillervision/s72b2/23/

Edited by Nillervision

one other thing to be picky about a free thing ;) ...

 

is there a way for the default volume to be less than 100%? it's intensely annoying when youtube and others force 100% usually when you left your volume up on your speakers, your kids are sleeping and/or you're at work ;)

 

works in firefox on mac btw ;) and chrome (latest stable didn't try in canary but guess it will)

 

in latest opera (all mac) and opera next (opera beta/dev) i get nothing playing - not sure whether it's the play function or the fileformat...

 

 

not sure whether this is relevant http://stackoverflow.com/questions/13218097/audio-tag-doesnt-work-in-firefox-and-opera

Edited by dap

  • Author

one other thing to be picky about a free thing ;) ...

 

is there a way for the default volume to be less than 100%? it's intensely annoying when youtube and others force 100% usually when you left your volume up on your speakers, your kids are sleeping and/or you're at work ;)

 

works in firefox on mac btw ;) and chrome (latest stable didn't try in canary but guess it will)

 

in latest opera (all mac) and opera next (opera beta/dev) i get nothing playing - not sure whether it's the play function or the fileformat...

 

 

not sure whether this is relevant http://stackoverflow.com/questions/13218097/audio-tag-doesnt-work-in-firefox-and-opera

To start the player with say 50% volume do this:

Change the value of the volume slider in the html from 10 to 5:

<input id="volKnob" type="range" min="0" max="10" value="5" step="1" />

 

As the very last line in the registerEvents function in the javascript insert this line:

volFunc ();

That should do the trick :)

 

EDIT: I understand that the default maximum volume can be anoying and I will consider if the volume function should be called on load by default. On the other hand full volume is the default value of the audio tag so it might be most semantic to leave all ajustment of the volume to the end user.

Edited by Nillervision

i agree with leaving defaults as they are but in this case i think it's wrong ;) but if designers/developers can preset the level then that's more than good enough for me ;)

Create an account or sign in to comment

Account

Navigation

Search

Search

Configure browser push notifications

Chrome (Android)
  1. Tap the lock icon next to the address bar.
  2. Tap Permissions → Notifications.
  3. Adjust your preference.
Chrome (Desktop)
  1. Click the padlock icon in the address bar.
  2. Select Site settings.
  3. Find Notifications and adjust your preference.