简体   繁体   中英

html5 audio Setting volume with javascript not effective

I have this simple tiny .mp3 that has to be played on new message. It plays well but i can't seam to control the volumelevel of it. I've this Jfidle http://jsfiddle.net/Ls9ef0zo/14/ prepared with a visual audio element. Ofcourse i don't want it to be visible in the real environment.

 <input id="volumeslider" type="range" min="0" max="1" step="0.1" value="0.5"
  oninput="outputUpdate(value)"/>                                                       


  var newmsgsound = document.createElement('audio');
  newmsgsound.setAttribute('src',
  http://chat.transonly.nl/sounds/sound_1.mp3');
  newmsgsound.setAttribute('id', 'newmsgsound');
  newmsgsound.setAttribute('controls', 'controls');
  body.appendChild(newmsgsound);

  function outputUpdate(vol) {
  var audiolevel = document.getElementById('newmsgsound');
  audiolevel.volume=vol;
  }

edit Not sure where to update the question as partialy answered so i'll do it here?

Thanks to the anwers provided the audio-element actually responds now to the slider-event however!..In my own environment (Not Fidle) The sound played by the audio-element is not affected by it. I can see it is responding. Even when i set it to 'Mute' on the audio-element itself the sound gets played out loud. Isn't that ought?

edit2* I should be very ashamed now!!! I was hearing the sound of a browser i'd hidden and was sending test messages to that one. :-) It's ok now!

Update:

Your code is fine. You need to define the outputUpdate() function before referring it in volumeslider. You simply need to tweak jsfiddle to have "no wrap in body".

 <script>
     var newmsgsound = document.createElement('audio');
     newmsgsound.setAttribute('src', 'http://chat.transonly.nl/sounds/sound_1.mp3');
     newmsgsound.setAttribute('id', 'newmsgsound');
     newmsgsound.setAttribute('controls', 'controls');
     document.body.appendChild(newmsgsound);

     function outputUpdate(vol) {      
        var audiolevel = document.getElementById('newmsgsound');
        audiolevel.volume=vol;
    }   
    </script>

    <input id="volumeslider" type="range" min="0" max="1" step="0.1" oninput="outputUpdate(value)"/>    

Here's the plunkr

You function output update is not used now.

try something like this.

 var newmsgsound = document.createElement('audio');
 newmsgsound.setAttribute('src', 'http://chat.transonly.nl/sounds/sound_1.mp3');
 newmsgsound.setAttribute('id', 'newmsgsound');
 newmsgsound.setAttribute('controls', 'controls');
 document.body.appendChild(newmsgsound);
 var audiolevel = document.getElementById('newmsgsound');
 var value = document.getElementById('volumeslider').value;
 audiolevel.volume=value;

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