首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何使用Javascript播放mp3?

如何使用Javascript播放mp3?
EN

Stack Overflow用户
提问于 2012-07-04 22:20:57
回答 9查看 106.7K关注 0票数 35

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

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

现在,给出这个列表,我如何点击一个按钮(播放)并让网站播放列表中的第一个mp3?(我也知道音乐在网站的什么地方)

EN

回答 9

Stack Overflow用户

回答已采纳

发布于 2012-07-04 22:39:28

如果你想要一个能在旧浏览器上工作的版本,我做了这个库:

代码语言:javascript
复制
// 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;
    }
}

文档:

Sound有三个参数。声音的source url、volume (从0100)和loop (true表示循环,false表示不循环)。

stop允许在后面start (与remove相反)。

init重新设置参数音量和循环。

示例:

代码语言:javascript
复制
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
票数 28
EN

Stack Overflow用户

发布于 2012-07-04 22:37:06

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

票数 111
EN

Stack Overflow用户

发布于 2012-07-04 22:28:13

您可能希望使用新的HTML5 audio元素来创建Audio对象、加载mp3并播放它。

由于浏览器的不一致,这个示例代码有点长,但它应该经过一些调整就能满足您的需求。

代码语言:javascript
复制
//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元素。

票数 9
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11330917

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档