为jquery,javascript等声音元素数组创建一个音频对象

时间:2015-03-05 10:01:01

标签: javascript jquery arrays audio

我目前有很多像这样的声音元素

var AudioGood = document.createElement('audio');
AudioGood.controls = true;
AudioGood.src = 'sounds/good.wav';
AudioGood.volume=0.5;

var AudioWrong = document.createElement('audio');
AudioWrong.controls = true;
AudioWrong.src = 'sounds/wrong.wav';
AudioWrong.volume=0.5;

等等。我不喜欢那样。我尝试做类似

的事情
function track (name,controls,src,volume,loop){
    this.name = name;
    this.controls = controls;
    this.src = src;
    this.volume = volume;
    this.loop = loop;
}

var music = [
new track ('AudioGood',true,'sounds/good.wav',0.5,false),
new track ('AudioWrong',true,'sounds/wrong.wav',0.5,false),
new track ('musicBackground',true,'sounds/background.ogg',0.5,true),
new track ('AudioDrop',true,'sounds/drop.wav',0.5,false),
new track ('AudioCard',true,'sounds/card.wav',0.5,false)
];

但我需要创建一个音频元素document.createElement('audio')。我该怎么办?这可能是一个愚蠢的问题,但请怜悯......

2 个答案:

答案 0 :(得分:2)

最合乎逻辑的方法是创建一个指向DOM元素的element属性:

function Track (name, controls, src, volume, loop) {
    this.name = name;
    this.element = document.createElement('audio');
    this.element.controls = controls;
    this.element.src = src;
    this.element.volume = volume;
    this.element.loop = loop;
}

即使this.element的属性可公开访问,在轨道原型上创建必要的getter / setter方法也是一个很好的设计选择。例如:

Track.prototype.setVolume = function(value) {
    this.element.volume = value;
};

答案 1 :(得分:0)

您可以只从track函数返回音频元素,而不是使用track作为构造函数。

     function track (name,controls,src,volume,loop) {

            var  audio = document.createElement('audio');

          audio.name = name;
          audio.controls = controls;
          audio.src = src;
          audio.volume = volume;
          audio.loop = loop;

         return audio;

    };

var music = [
   track('AudioGood',true,'sounds/good.wav',0.5,false),
   track('AudioWrong',true,'sounds/wrong.wav',0.5,false),
   track('musicBackground',true,'sounds/background.ogg',0.5,true),
   track('AudioDrop',true,'sounds/drop.wav',0.5,false),
   track('AudioCard',true,'sounds/card.wav',0.5,false)
];