Explain Codes LogoExplain Codes Logo

Play an audio file using jQuery when a button is clicked

javascript
event-listeners
audio-control
browser-compatibility
Nikita BarsukovbyNikita BarsukovยทNov 12, 2024
โšกTLDR

Here's how you play audio on button click with jQuery:

// HTML: Put your mixtape here <audio id="audio" src="your-audio.mp3"></audio> // HTML: Your 'Play' button, aka your DJ <button id="play">Play</button> // jQuery: Let the music play ๐ŸŽต $('#play').click(function() { $('#audio')[0].play(); });

Just plug in your "your-audio.mp3" (your tune) and push the #play button to start your audio.

Ensuring audio gaze and readiness

In the real world, we call this "Making sure your DJ is awake before dropping the beat":

// Waiting for the green light from the DJ booth $('#audio').on('canplay', function() { console.log("DJ is awake!"); });

Here, we're ensuring the audio's readiness with the canplay event. An awake DJ is... usually a good thing.

The fine art of flexible audio control

Too many tracks for a single DJ? No worry, we got an army of DJs:

// Making clones of your DJ var audio = new Audio(); audio.src = 'your-audio.mp3'; audio.id = 'cloneDJ'; $('body').append(audio); $('#play').click(function() { $('#cloneDJ')[0].play(); });

Creating <audio> elements dynamically gives you more control - like having a control room full of DJs!

Stopping, resetting and replaying audio

Your DJs also need breaks. Here's how you give them that break and cue them up again:

// Give your DJ a little break - 'Stop' button $('#stop').click(function() { var audio = $('#audio')[0]; audio.pause(); // Freeze! audio.currentTime = 0; // Back to the starting line }); // And... Action! - replay the audio when it ends $('#audio').on('ended', function() { this.currentTime = 0; // From the top! this.play(); // Let's go again! });

This way, you are treating your DJ right, by re-setting the audio to the start with currentTime and preventing mixer's burn-out using pause().

Catering to all browsers, not just the headliner

For the audio to play across various browsers, include multiple formats:

<audio id="audio"> <source src="your-audio.mp3" type="audio/mpeg"> <source src="your-audio.ogg" type="audio/ogg"> </audio> <button id="play">Play</button>

For those audio-snobs (browsers) that only play certain formats, use canPlayType():

if ($('#audio')[0].canPlayType('audio/mpeg')) { // DJ, play that tune! } else { // Sorry folks, time to upgrade your browser. ๐Ÿคทโ€โ™‚๏ธ }

Playing smoothly on different browsers is like being on a world tour!

How to preload audio like a real pro

Treat your audio files to some VIP treatment - let them in before the rush:

// Give your audio the VIP pass - no waiting in line! $('#audio').attr('preload', 'auto'); // Open the gates! $('#audio')[0].load();

That's your red carpet treatment right there. This ensures your audio will be ready to play instantly.

Keep your fans (users) updated

Be your fan's best friend - keep them informed:

// Letting your fans know - 'We're halfway through the track!' $('#audio').on('timeupdate', function() { $('#currentTime').text(this.currentTime); // Now playing: 2:00/4:00 });

This way, everyone knows when the drop is coming!