将 javascript 变量值放入音频的 src
Put javascript variable value in src of audio
正在使用 embed 播放 Flash SWF 文件以在没有控件的情况下播放随机背景音乐。由于 Flash
即将消失,我想使用带有控件的 <audio>
标记来替换它。有一个名为 music 的文件夹,其中包含多个名称简单的 MP3 文件(Song1.mp3、song2.mp3 ,ETC。)。我有一个脚本可以为变量 Whichsong
生成一个随机数
(WhichSong="Music/song"+(Math.floor(Math.random()*23))+".swf"
该变量用作要播放的歌曲的路径
(document.write('<embed src="'+WhichSong+'" quality="high" width="0" height="0")
我在这里看到的代码建议我可以使用类似的方法将 URL 信息放入 <Audio SRC="'+WhichSong+'" >
标记中。但是,我尝试过的任何事情都没有奏效。我试过 with/without 引号,with/without +,with/without ',以及所有的各种组合.什么都不管用。没有声音,没有控制。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div align="center" id="soundtrack"></div>
<script type="text/javascript">
var WhichSong="Music/song"+(Math.floor(Math.random()*23))+".mp3"
document.getElementById('soundtrack').innerHTML="<audio controls id='background_audio1'><source src='music/5.mp3'>Your browser does not support the audio element.</audio>";
</script>
</body>
</html>
如果整个内容都被引用,WhichSong
变量将不会在您的 innerHTML 字符串中被解释。您需要打破引号:
"<source src=\"" + WhichSong + "\"></source>"
,或使用 template string,如下例所示。除此之外好像还好。
function setSong () {
const WhichSong="Music/song"+(Math.floor(Math.random()*23))+".mp3"
document.getElementById('soundtrack').innerHTML=`
<audio controls
id='background_audio1'>
<source src='${WhichSong}' />
Your browser does not support the audio element.
</audio>
<div>${WhichSong}</div>
`;
}
<div id="soundtrack"></div>
<button onClick="setSong()">Set Song</button>
正在使用 embed 播放 Flash SWF 文件以在没有控件的情况下播放随机背景音乐。由于 Flash
即将消失,我想使用带有控件的 <audio>
标记来替换它。有一个名为 music 的文件夹,其中包含多个名称简单的 MP3 文件(Song1.mp3、song2.mp3 ,ETC。)。我有一个脚本可以为变量 Whichsong
(WhichSong="Music/song"+(Math.floor(Math.random()*23))+".swf"
该变量用作要播放的歌曲的路径
(document.write('<embed src="'+WhichSong+'" quality="high" width="0" height="0")
我在这里看到的代码建议我可以使用类似的方法将 URL 信息放入 <Audio SRC="'+WhichSong+'" >
标记中。但是,我尝试过的任何事情都没有奏效。我试过 with/without 引号,with/without +,with/without ',以及所有的各种组合.什么都不管用。没有声音,没有控制。
示例代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<div align="center" id="soundtrack"></div>
<script type="text/javascript">
var WhichSong="Music/song"+(Math.floor(Math.random()*23))+".mp3"
document.getElementById('soundtrack').innerHTML="<audio controls id='background_audio1'><source src='music/5.mp3'>Your browser does not support the audio element.</audio>";
</script>
</body>
</html>
如果整个内容都被引用,WhichSong
变量将不会在您的 innerHTML 字符串中被解释。您需要打破引号:
"<source src=\"" + WhichSong + "\"></source>"
,或使用 template string,如下例所示。除此之外好像还好。
function setSong () {
const WhichSong="Music/song"+(Math.floor(Math.random()*23))+".mp3"
document.getElementById('soundtrack').innerHTML=`
<audio controls
id='background_audio1'>
<source src='${WhichSong}' />
Your browser does not support the audio element.
</audio>
<div>${WhichSong}</div>
`;
}
<div id="soundtrack"></div>
<button onClick="setSong()">Set Song</button>