Reputation: 1510
I'm currently creating an audio element with JS like this :
var newAE = document.createElement('audio');
newAE.id = "ios-audio";
newAE.src = obj.media;
document.getElementById('ios').appendChild(newAE);
Which is great, but I need to also programmatically set the type
based on the content of the incoming obj.media
value.
type="audio/mpeg"
type="audio/ogg"
I thought this would work :
var enctype = 'audio/mpeg';
if (obj.media == "https://example.com/myaudiofile.ogg") {
enctype = 'audio/ogg';
}
var newAE = document.createElement('audio');
newAE.id = "ios-audio";
newAE.src = obj.media;
newAE.type = enctype;
document.getElementById('ios').appendChild(newAE);
But it doesn't create the type
parameter at all. I still end up with this in the DOM :
<audio id="ios-audio" src="https://example.com/myaudiofile.mp3"></audio>
When the desired result in this case would be :
<audio id="ios-audio" src="https://example.com/myaudiofile.mp3" type="audio/mpeg"></audio>
I guess I'm doing it wrong so could somebody point me in the right direction please?
Example below (without the mp3/ogg switch as it's irrelevant)
function create(media) {
var enctype = "audio/mpeg";
var newAE = document.createElement('audio');
newAE.id = "ios-audio";
newAE.src = media;
newAE.type = enctype;
document.getElementById('ios').appendChild(newAE);
var player = document.getElementById('ios-audio');
setTimeout(function() {
player.play();
console.log("playing");
console.log(player);
}, 50);
}
create('https://ia800508.us.archive.org/15/items/LoveThemeFromTheGodfather/02LoveThemeFromTheGodfather.mp3');
<div id="ios"></div>
Upvotes: 1
Views: 1072
Reputation: 44010
<source>
and [type]
I believe the [type]
attribute belongs to the <source>
tag. An <audio>
tag can only have one [src]
attribute and when more than one is needed, <source>
tags are added for each [src]
. The [type]
attribute is needed to designate the MIME for multiple [src]
.
if demo does not function on SO, review this functioning demo on Plunker
var aTag = document.createElement('audio');
aTag.id = 'a0';
aTag.controls = true;
var sMP3 = document.createElement('source');
sMP3.src = 'https://instaud.io/_/2JCu.mp3';
sMP3.type = 'audio/mpeg';
var sOGG = document.createElement('source');
sOGG.src = 'https://instaud.io/_/2Mxg.ogg';
sOGG.type = 'audio/ogg';
aTag.appendChild(sMP3);
aTag.appendChild(sOGG);
document.querySelector('.dock').appendChild(aTag);
<fieldset class='dock'>
<legend>Audio and Source Tags</legend>
</fieldset>
Upvotes: 2