Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
157 views
in Technique[技术] by (71.8m points)

How to implement fast-forward functionality for an audio player using JavaScript

I'm trying to implement fast-forward in my app. I've added an event listener to the fast-forward button which adds ten seconds to the current time of the audio clip. The problem is, it only works on the first click of the fast-forward button.

I'm using the timeupdate event display the current time of the audio on screen but I need the time to be ten seconds larger every time I click the button. What am I missing? Here's the eventlistener on the audio track to display the forwarded time

function forwardTenSecs (audio_track){
    audio_track.addEventListener('timeupdate', () => {
            const currentTime = Math.floor(audio_track.currentTime);
            const duration = Math.floor(audio_track.duration);
            track_time.innerText = `${plusTenSecs(currentTime)} / ${format_time(duration)}`;
    }, false);
}

Here's the function I use to format the audio current time and to add ten seconds to it.

function plusTenSecs(time){
    let sec = Math.floor(time) + parseInt(10);
    let min = Math.floor( sec / 60 );
    if (min < 10) {
        min = '0' + min;
    }
    sec = Math.floor( sec % 60 );
    if (sec < 10) {
        sec = '0' + sec;
    }
    return min + ":"+ sec;
}

The idea is that every time I click the forward button, the plusTenSecs function should run, which in turn should make forwardTenSecs function run.

What am I missing?

question from:https://stackoverflow.com/questions/65517594/how-to-implement-fast-forward-functionality-for-an-audio-player-using-javascript

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
// Add eventListener to the fast-forward button
const btn = document.getElementById("btn").addEventListener('click', fastForward)

// add current time to 10 seconds in every click
function fastForward() {
    audio_track.currentTime += 10;
}

You can try the demo here: https://jsfiddle.net/mu8cz7f4/ The demo audio is only 1-2 seconds so I set just adding 0.1 second every click


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...