为音频播放/静音设置创建cookie

时间:2018-04-26 10:57:25

标签: javascript html html5 cookies

我有以下HTML:

<audio autoplay id="background_audio">
  <source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>

<a href="#" id="mute">Play/mute sound</a>

以下JS:

var audio = document.getElementById('background_audio');

document.getElementById('mute').addEventListener('click', function (e)
{
    e = e || window.event;
    audio.muted = !audio.muted;
    e.preventDefault();
}, false);

您可以在这里找到JSFiddle

此脚本的作用是静音并继续播放具有background_audio id的音频文件。

我在SO和谷歌的JS上花了最后一天的时间,但是无法让事情发挥作用(不知道如何调试JS是我猜的主要问题)。

点击“mute”ID时,我需要创建一个Cookie。然后我需要验证cookie是否已设置,如果已设置,则将存储在cookie中的值分配给audio.muted。如果未设置cookie,则应播放声音。

虽然我知道如何在PHP中创建条件并设置cookie,但JS是我的弱点,每当我尝试某些东西时,它最终都无法正常工作。

如何修改脚本以设置cookie或创建会话,以便当用户将声音静音在一个页面上时,它也可以在其他页面上保持这种状态?

请您提供一个如何完成工作的实例?

1 个答案:

答案 0 :(得分:1)

这可能不是最优雅的解决方案,但这是我提出的。我已经对所有内容进行了评论,因此应该很容易理解正在发生的事情。

由于StackOverflow和其他人限制在代码中设置cookie(这是可以理解的),我在这里提出了一个工作示例:https://dev.pawdesigns.ca/js-cookies/

//Get audio element.
var audio = document.getElementById("background_audio");

//Get current time/date.
var date = new Date();
date.setTime(+ date + (1 * 24 * 60 * 60 * 1000)); // _days_ * hours/day *  mins/hour * sec/min * ms/s (Change first number to change how many days cookie is valid for)

//Check if mute cookie exists.
if (document.cookie.indexOf("mute=") == -1) {
    //It does not, lets create it!
    document.cookie = "mute=" + false + ";expires=" + date.toGMTString() + "; path=/";
    //Start playing audio!
    audio.play();
} else {
    //Check if mute cookie is set to false.
    if (getCookie("mute") == "false") {
        //It is, lets play!
        audio.play();
    }
}

function getCookie(name) {
    // getCookie function by Chirp Internet: www.chirp.com.au
    var re = new RegExp(name + "=([^;]+)");
    var value = re.exec(document.cookie);
    return value != null ? unescape(value[1]) : null;
}

//On play/mute button/link click.
document.getElementById("mute").addEventListener("click",function(e) {
    e = e || window.event;
    if (getCookie("mute") == "false") {
        //If mute cookie is set to false, mute audio.
        audio.muted = true;
    } else {
        //If mute cookie is set to true, unmute audio.
        audio.muted = false;
        //Check if audio has been started before.
        if (audio.paused || audio.currentTime > 0) {
            //It has not, lets play it!
            audio.play();
        }
    }
    //Set/update mute cookie with new audio muted value.
    document.cookie = "mute=" + audio.muted + ";expires=" + date.toGMTString() + "; path=/";
    e.preventDefault();
}, false);
<audio id="background_audio">
    <source src="https://sporedev.ro/pleiade/hol.mp3" type="audio/mpeg">
</audio>

<a href="#" id="mute">Play/mute sound</a>

相关问题