Establecí 4 tiempos de espera para audios en mi aplicación y necesito detener los audios después de que el usuario haga clic. La función macro funciona correctamente, sin embargo, clearTimout no detiene el sonido. Alguien sabe como borrarlo?
export function handlePlay(audio) { audio.currentTime = 0; return audio.play(); } export function handleConversation(clear) { const timer1 = () => setTimeout(() => { handlePlay(conversation[Math.floor(Math.random() * conversation.length)]); }, TIME1); const timer2 = () => setTimeout(() => { handlePlay(conversation[Math.floor(Math.random() * conversation.length)]); }, TIME2); const timer3 = () => setTimeout(() => { handlePlay(conversation[Math.floor(Math.random() * conversation.length)]); }, TIME3); const timer4 = () => setTimeout(() => { handlePlay(conversation[Math.floor(Math.random() * conversation.length)]); }, TIME4); if (clear) { console.log('enter clear'); return () => { clearTimeout(timer1); clearTimeout(timer2); clearTimeout(timer3); clearTimeout(timer4); }; } timer1(); timer2(); timer3(); timer4(); }después de clearTimeouts llame a este código
audio.pause(); audio.currentTime = 0;Aquí una sugerencia de lo que podrías hacer.
Supongo que esto podría mejorarse aún más con respecto a cómo se usa esta función handleConversation, realmente no entendí la idea y todavía hay algunas inconsistencias...
function createAudio(track) { track.audio = conversation[Math.floor(Math.random() * conversation.length)]; } export class Track { constructor(time) { this.time = time; this.timeoutid = 0; this.audio = new Audio(); } timer() { this.timeoutid = setTimeout(() => { createAudio(this); handlePlay(this.audio); }, TIME1); } play() { this.audio.currentTime = 0; this.audio.play(); } stop() { this.audio.pause(); this.audio.currentTime = 0; clearTimeout(this.timeoutid) } } export function handleConversation(clear) { const track1 = new Track(TIME1); const track2 = new Track(TIME2); const track3 = new Track(TIME3); const track4 = new Track(TIME4); // this part actually doesn't make a lot of sense, since all tracks will be recreated each time the function is called. // I don't really understand how this is used. // I imagine the tracks should more likey be stored outside the function in a persistent object. // I will modify my answer if you provide more details about how you use handleConversation if (clear) { console.log('enter clear'); return () => { [track1, track2, track3, track4].forEach(track => { track.stop() }); }; } [track1, track2, track3, track4].forEach(track => { track.timer() }); }