即使在JavaScript中调用pause()后音频也不会暂停

问题描述 投票:0回答:1

我正在尝试使用 JavaScript 实现自定义铃声功能。音频播放正确,但是当我尝试使用 stopRingtone() 函数暂停它时,即使 console.log 输出显示调用了 pause() 方法,音频也会继续播放。 这是我播放音频的代码:

function playCustomeRingtone(ringtonePath) {
    audioId.value = `audio-${Date.now()}`; 
    // Find the existing audio element
    let audioElement = document.getElementById(audioId.value);
    if (!audioElement) {
        // If the audio element doesn't exist, create it
        audioElement = new Audio(ringtonePath);
        audioElement.id = audioId.value;
        document.body.appendChild(audioElement);
    } else {
        // If it exists, update its source
        audioElement.src = ringtonePath;
    }
    audioElement.preload = "auto";   
    audioElement.onerror = () => {
        console.error("Failed to load audio. Falling back to default.");
        audioElement.src = ringtonePath;
        audioElement.play().catch(error => {
            console.error('Error playing the fallback audio:', error);
        });
    };

    // Play the audio
    audioElement.play().then(() => {
        console.log('Playing audio with ID:', audioId.value);
    }).catch(error => {
        console.error('Error playing the audio:', error);
    });

    return audioId.value;
}

要停止音频,我使用此功能:

function stopRingtone() {
    const audioElement = document.getElementById(audioId.value);
    if (audioElement) {
        audioElement.pause();
        audioElement.currentTime = 0;
        setTimeout(() => {
            console.log(`Paused audio with ID: ${audioId.value}`);
            console.log('Audio paused state:', audioElement.paused);
            console.log('Audio current time:', audioElement.currentTime);
        }, 100);
    }
}


即使以下日志表明音频已暂停: 控制台.log(

Paused audio with ID: ${audioId.value}
); console.log('音频暂停状态:',audioElement.paused); console.log('音频当前时间:',audioElement.currentTime); 音频继续播放。 更改 DOM 元素以确保正确引用它。 添加超时以确保在检查暂停状态之前有延迟。 检查音频状态(audioElement.paused),返回true,但音频仍在播放。 为什么音频不暂停?如何确保音频确实停止?

javascript html audio browser audio-streaming
1个回答
0
投票
let audioId = { value: null }; // Ensure audioId is defined globally

function playCustomeRingtone(ringtonePath) {
    audioId.value = `audio-${Date.now()}`;
    let audioElement = document.getElementById(audioId.value);

    if (!audioElement) {
        audioElement = new Audio(ringtonePath);
        audioElement.id = audioId.value;
        document.body.appendChild(audioElement);
    } else {
        // Update source only if needed (prevent unnecessary resets)
        if (audioElement.src !== ringtonePath) {
            audioElement.src = ringtonePath;
        }
    }

    audioElement.preload = "auto";   
    audioElement.onerror = () => {
        console.error("Failed to load audio. Falling back to default.");
        audioElement.src = ringtonePath;
        audioElement.play().catch(error => {
            console.error('Error playing the fallback audio:', error);
        });
    };

    audioElement.play().then(() => {
        console.log('Playing audio with ID:', audioId.value);
    }).catch(error => {
        console.error('Error playing the audio:', error);
    });

    return audioId.value;
}

function stopRingtone() {
    const audioElement = document.getElementById(audioId.value);
    if (audioElement) {
        audioElement.pause();
        audioElement.currentTime = 0;

        setTimeout(() => {
            console.log(`Paused audio with ID: ${audioId.value}`);
            console.log('Audio paused state:', audioElement.paused);
            console.log('Audio current time:', audioElement.currentTime);

            // Check if the audio really stopped
            if (!audioElement.paused || audioElement.currentTime !== 0) {
                console.warn('Audio did not stop as expected. Trying again...');
                audioElement.pause();
                audioElement.currentTime = 0;
            }
        }, 100);
    }
}

确保audioId是全局定义的,以便可以在playCustomeRingtone和stopRingtone中引用它。 在播放之前设置源,以防止可能影响播放/暂停流程的不必要的重置。 在 stopRingtone 中添加了重试检查,以确保音频停止。

© www.soinside.com 2019 - 2024. All rights reserved.