我在我的网站上有一个包含多个mp3文件的目录。
我使用PHP动态创建了这些mp3的列表,并与其相关联拖放功能,我可以选择一个列表中要播放的mp3。
现在,如果给定了一个这样的列表,如何点击一个按钮(播放)让网站播放列表中的第一个mp3?(我也知道音乐在网站上的位置)
我在我的网站上有一个包含多个mp3文件的目录。
我使用PHP动态创建了这些mp3的列表,并与其相关联拖放功能,我可以选择一个列表中要播放的mp3。
现在,如果给定了一个这样的列表,如何点击一个按钮(播放)让网站播放列表中的第一个mp3?(我也知道音乐在网站上的位置)
new Audio('<url>').play()
new Audio
不会导致内存泄漏吗? - Rodrigo<audio>
标签的工作方式与 <img>
标签相同;您可以更新 src
属性以更改元素的文件。 - Ties如果你需要适用于旧浏览器的版本,我已经制作了这个库:
// source: https://dev59.com/oWgu5IYBdhLWcg3wbGil#11331200
function Sound(source, volume, loop)
{
this.source = source;
this.volume = volume;
this.loop = loop;
var son;
this.son = son;
this.finish = false;
this.stop = function()
{
document.body.removeChild(this.son);
}
this.start = function()
{
if (this.finish) return false;
this.son = document.createElement("embed");
this.son.setAttribute("src", this.source);
this.son.setAttribute("hidden", "true");
this.son.setAttribute("volume", this.volume);
this.son.setAttribute("autostart", "true");
this.son.setAttribute("loop", this.loop);
document.body.appendChild(this.son);
}
this.remove = function()
{
document.body.removeChild(this.son);
this.finish = true;
}
this.init = function(volume, loop)
{
this.finish = false;
this.volume = volume;
this.loop = loop;
}
}
文档:
Sound
接受三个参数:音频的 source
url,volume
(介于 0
到 100
之间),以及 loop
(值为 true
可循环播放,值为 false
不可循环播放)。
stop
允许在音频播放后再次启动(与 remove
相反)。
init
重新设置音频的音量和循环参数。
示例:
var foo = new Sound("url", 100, true);
foo.start();
foo.stop();
foo.start();
foo.init(100, false);
foo.remove();
//Here you you cannot start foo any more
你可能想要使用新的HTML5 audio
元素创建一个Audio
对象,加载mp3并播放。
由于浏览器不一致性,这个示例代码有点冗长,但只需稍加调整即可满足您的需求。
//Create the audio tag
var soundFile = document.createElement("audio");
soundFile.preload = "auto";
//Load the sound file (using a source element for expandability)
var src = document.createElement("source");
src.src = fileName + ".mp3";
soundFile.appendChild(src);
//Load the audio tag
//It auto plays as a fallback
soundFile.load();
soundFile.volume = 0.000000;
soundFile.play();
//Plays the sound
function play() {
//Set the current time for the audio file to the beginning
soundFile.currentTime = 0.01;
soundFile.volume = volume;
//Due to a bug in Firefox, the audio needs to be played after a delay
setTimeout(function(){soundFile.play();},1);
}
编辑:
为了添加 Flash 支持,你需要在 audio
标签内部追加一个 object
元素。
享受它 ;)
<html>
<head>
<title>Play my music....</title>
</head>
<body>
<ul>
<li>
<a id="PlayLink" href="http://www.moderntalking.ru/real/music/Modern_Talking-You_Can_Win(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">U Can Win</a>
</li>
<li>
<a id="A1" href="http://www.moderntalking.ru/real/music/Modern_Talking-Brother_Louie(DEMO).mp3" onclick="pplayMusic(this, 'music_select');">Brother Louie</a>
</li>
</ul>
<script type="text/javascript" src="http://mediaplayer.yahoo.com/js"></script>
</body>
</html>
<audio>
标签。 - millimoose