Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

pause an audio with javascript

enter image description herecan anyone help me with this code when I clicked a start button the async function executed which contains a for loop that loops through array audios that contain words when the audio is played the word is highlighted. i want to implement pause function which pause the audio and then when I back to click start or another button i created continue with the current paused audio . anyone know the better way to do this or give me a reference .

    const startBtn = document.querySelector('.start');
    const pauseBtn = document.querySelector('.pause');
    const stopBtn = document.querySelector('.stop');
    // words dom selectors 

    const spans = document.getElementsByTagName('span');
    const audios = document.getElementsByTagName('audio');
    

    // audios Dom selector
    
    // function for wait 
    const wait =  (sec)=>{
        return new Promise(resolve =>{
            setTimeout(resolve, sec * 1000)
        })
    }
    

    startBtn.addEventListener('click', ()=>{
        x += 1
        if(x === 1){
            play().then(()=>{
                x = 0;
            })
        }

      
    })

   pauseBtn.addEventListener('click', ()=>{
    
    })

    let currentAudio;
    let x = 0;
    const play = async ()=>{

        for(let i = 0; i < spans.length; i++){
            currentAudio = audios[i];
            if(currentAudio.paused === false) return;
            audios[i].play();
            changeStyle(spans[i], audios[i].duration);
            await wait(audios[i].duration);
        }
        return 'audio finished';
    }


   
    const changeStyle = (element, sec)=>{
        element.classList.add('highlight');
        setTimeout(()=>{
            element.classList.remove('highlight')
        }, sec * 1000)
    }

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

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...