Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
HTML5 audio control stop button
HTML5 audio elements don't have a built-in stop button, but you can create one by combining the pause() method with resetting the currentTime property.
Basic Stop Function
To stop audio playback, pause the audio and reset its current time to zero:
<audio id="myAudio" controls>
<source src="/audio/sample.mp3" type="audio/mpeg">
</audio>
<button onclick="stopAudio()">Stop</button>
<script>
function stopAudio() {
var myPlayer = document.getElementById('myAudio');
myPlayer.pause();
myPlayer.currentTime = 0;
}
</script>
Complete Example with Play/Stop Controls
<audio id="audioPlayer">
<source src="/audio/sample.mp3" type="audio/mpeg">
</audio>
<button onclick="playAudio()">Play</button>
<button onclick="stopAudio()">Stop</button>
<script>
var audio = document.getElementById('audioPlayer');
function playAudio() {
audio.play();
}
function stopAudio() {
audio.pause();
audio.currentTime = 0;
}
</script>
Using jQuery
You can also implement the stop functionality using jQuery:
<audio id="myAudio">
<source src="/audio/sample.mp3" type="audio/mpeg">
</audio>
<button id="stopButton">Stop</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$("#stopButton").click(function() {
var audio = document.getElementById('myAudio');
audio.pause();
audio.currentTime = 0;
});
</script>
Key Points
- pause(): Stops playback but keeps the current position
- currentTime = 0: Resets playback to the beginning
- Combine both methods to create a true "stop" function
- Works with both vanilla JavaScript and jQuery
Conclusion
Creating a stop button for HTML5 audio requires pausing playback and resetting the currentTime to zero. This approach works consistently across all modern browsers and provides the expected stop functionality.
Advertisements
