Reputation: 503
I have currently a number of sound elements like this
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;
and so on. I don;t like that. I try to make something like
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)
];
But I need to create a audio element, document.createElement('audio'). how would I do that? it's probably a stupid question, but please be merciful...
Upvotes: 3
Views: 1890
Reputation: 3610
Rather than using track
as a constructor, you can just return an audio element from your track
function.
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)
];
Upvotes: 0
Reputation: 193271
The most logical way is to create a property like element
pointing to 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;
}
Also even though properties of this.element
are publicly accessible, it would be good design choice to create necessary getter/setter methods on track prototype. For example:
Track.prototype.setVolume = function(value) {
this.element.volume = value;
};
Upvotes: 2