Play an audio file using jQuery when a button is clicked
Here's how you play audio on button click with jQuery:
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":
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:
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:
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:
For those audio-snobs (browsers) that only play certain formats, use canPlayType()
:
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:
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:
This way, everyone knows when the drop is coming!
Was this article helpful?