如何使用Javascript播放MP3?

aF.*_*aF. 26 html javascript mp3

我的网站上有一个目录,里面有几个mp3.我使用php在网站上动态创建它们的列表.

我还有一个与它们相关的拖放功能,我可以选择要播放的mp3列表.

现在,给出该列表,我如何点击按钮(播放)并让网站播放列表中的第一个mp3?(我也知道音乐在网站上的位置)

Tie*_*ies 87

new Audio('<url>').play()

  • 完整文档:https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement (5认同)

Mag*_*eek 24

如果你想要一个适用于旧浏览器的版本,我已经创建了这个库:

// source: https://stackoverflow.com/a/11331200/4298200
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;
    }
}
Run Code Online (Sandbox Code Playgroud)

文档:

Sound有三个论点.声音的url,音量(从0到100)和循环(true到循环,false不循环).
stop允许start之后(与之相反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
Run Code Online (Sandbox Code Playgroud)

  • 你有音乐的长度吗? (2认同)

Jef*_*ney 7

您可能希望使用新的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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:

要添加Flash支持,您可以objectaudio标记内附加一个元素.