简体   繁体   中英

Javascript play audio when loaded

so I have a code for volume slider. What it does is that it plays sound when you have changed volume after loading the slider. For example if default value of the slider is 50 it wont play sound right after loading the audio file, you need to change value to higher or lower so sound can come out. So I need help with JavaScript. What can I do so it starts playing the sound whenever is loaded?

Full code : https://www.w3schools.com/code/tryit.asp?filename=FQZVZUX36JFD

JS:

$("#volume").slider({
min: 0,
max: 100,
value: 50,
    range: "min",
slide: function(event, ui) {
    setVolume(ui.value / 100);
}
});

var myMedia = document.createElement('audio');
$('#player').append(myMedia);
myMedia.id = "myMedia";

playAudio('http://listen.shoutcast.com/newfm64aac-', 0);

function playAudio(fileName, myVolume) {
        myMedia.src = fileName;
        myMedia.setAttribute('loop', 'loop');
    setVolume(myVolume);
    myMedia.play();
}

function setVolume(myVolume) {
var myMedia = document.getElementById('myMedia');
myMedia.volume = myVolume;
}

Google最近发布了一个浏览器更新,可防止媒体元素的初始播放或自动播放 (注意:不是此答案的解决方案,而是类似情况的潜在解决方案。)

You're setting the initial volume to zero with this call:

playAudio('http://listen.shoutcast.com/newfm64aac-', 0);

To have it load at a default of 50 your call should be:

playAudio('http://listen.shoutcast.com/newfm64aac-', 50);

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