简体   繁体   中英

Html 5 audio local storage

I have to handle with the behaviour of an audio element in an HTML page. The audio starts when the user arrives on the page. I'd like to not play it again if he reaches again the page during the same session. I tried that code but it does not work. Do you have some suggestion about it? thank you very much

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<audio controls autoplay class="hidden-xs" style=" position:fixed; right:0; bottom:0; z-index:99999999999">
    <source src="music_bbms.mp3" type="audio/mpeg">
    Your browser does not support the audio element.
</audio>
<script>
    $(document).ready(function() {
        if (!localStorage.getItem('played') {
            $('.music').attr('autoplay', false);
            localStorage.setItem('played', true);
        }
    });
</script>

Here are some things I think might be wrong:

  1. There isn't any class .music on your audio element, so how can you change its attribute using that class selector. I have added an id to the audio element and used that id for selecting it.
  2. There was a closing parenthesis missing in the if condition, I have fixed that.
  3. I have assumed, we store the item value as a string in sessionStorage. sessionStorage has been used, because you said you want to keep track of this for only current session.
     <audio id="music" controls class="hidden-xs" style=" position:fixed; right:0; bottom:0; z-index:99999999999">
        <source src="music_bbms.mp3" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
    <script>
        $(document).ready(function() {
            if ( sessionStorage.getItem('played') != "true" ) {
                $('#music').get(0).play();
                sessionStorage.setItem('played', "true");
            }
        });
    </script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM