【问题标题】:Javascript: play a random song from an array (list)Javascript:从数组(列表)中播放一首随机歌曲
【发布时间】:2018-04-29 00:16:39
【问题描述】:

我想在网站上播放一首随机歌曲。曲调很短(最多几秒钟,它们不需要预加载或缓冲)。

这部分有效,歌曲数量可能不限,因为tunes.length会自动统计所有歌曲。

document.write在屏幕上显示随机歌曲网址的网址

tunes = new Array(
'"http://example.net/abcd.ogg"',
'"http://example.net/efgh.ogg"',
'"http://example.net/ijkl.ogg"'
)
var audiopath = (tunes[Math.floor(Math.random() * tunes.length)])
document.write (audiopath)

当 URL 被定义为常量时,这部分也可以工作。

var song = new audio('http://example.net/abcd.ogg');
song.play();

当我尝试将常量 URL 替换为变量 audiopath 时,它无法播放。
语法可能有什么问题吗? 我尝试在 URL '"@987654321@"'"@987654322@" 中使用和不使用单引号运行它

var song = new audio(audiopath);
song.play();

【问题讨论】:

    标签: javascript audio random shuffle


    【解决方案1】:

    在歌曲完全加载后处理开始播放可能会更好。像这样:

    let loaded = false;
    const song = new Audio();
    
    song.addEventListener('loadeddata', function() 
    {
        loaded = true;
        song.play();
    }, false);
    
    song.addEventListener('error' , function() 
    {
        alert('error loading audio');
    }, false);
    
    song.src = tunes[Math.floor(Math.random() * tunes.length)];
    

    【讨论】:

    • 谢谢,我试试。对于较长的歌曲,它看起来更通用。我做了不同的事情,将随机/随机播放功能保存为单独的 .js 文件,并将其用作播放器中的音频源。 .html 文件调用 .js 文件返回 var audio = new Audio(tunes[Math.floor(Math.random() * tunes.length)]) (我什至不知道 .js 文件中是否需要这一行,但它有效)。
    猜你喜欢
    • 2018-06-09
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-23
    相关资源
    最近更新 更多