Mo Howler
Mo Howler

Reputation: 13

audio.duration property not reseting when stop function is executed

when 'stop' is pressed the audio.duration doesn't reset to ("00:00"). I've tried various methods... Commented out in the function code.

function stop() {

audio.pause();
audio.currentTime = 0;
//audio.duration =  0;                                                                                                
//document.getElementById("duration-time").innerHTML = "00:00";
//document.getElementById("duration-time").textContent = "00:00";
//durtimetext.textContent = "00:00";
//durtimetext.innerHTML = "00:00";

}

The other two lines work, but just can't get Audio-duration span to reset to "00:00".

Cheers Coders

Upvotes: 0

Views: 179

Answers (3)

Kaiido
Kaiido

Reputation: 136708

You'd want to reset its src property:

const aud = document.querySelector("audio");
const btn = document.querySelector("button");
const log = document.querySelector("pre");

btn.onclick = function stop(evt) {
  aud.src = null;
};

setInterval(() => {
  log.textContent = aud.duration;
}, 1000);
<audio src="https://upload.wikimedia.org/wikipedia/en/transcoded/d/dc/Strawberry_Fields_Forever_(Beatles_song_-_sample).ogg/Strawberry_Fields_Forever_(Beatles_song_-_sample).ogg.mp3" controls></audio>

<button>stop</button>
<pre></pre>

Upvotes: 0

Jon Baltz
Jon Baltz

Reputation: 232

audio.duration just shows the length of the audio, not your place in the playback. The property is read-only

https://www.w3schools.com/Jsref/prop_audio_duration.asp

Upvotes: 1

Kavinda Senarathne
Kavinda Senarathne

Reputation: 2004

Try this :

function getDuration(src, destination) {
    var audio = new Audio();
    $(audio).on("loadedmetadata", function(){
        destination.textContent = audio.duration;
    });
    audio.src = src;
}

and then invoke getDuration as needed like this

var span = createOrGetSomeSpanElement();
getDuration("./audio/2.mp3", span);

Upvotes: 0

Related Questions