3

How do I deploy a selected audio file using JavaScript via the <audio> tag in HTML5? My code is like this:

<audio controls id="audio1">
    <source  src="" type="audio/ogg">
<source  src="" type="audio/mpeg">
</audio>

I don't want to give src manually. Instead, I want to set it dynamically via JavaScript.

In JavaScript, for selecting the src from files:

document.querySelector('#fileSelect').addEventListener('click', function(e) {
       // Use the native click() of the file input.
     audio.src = document.querySelector('#fileElem').click();
}, false);

I'd welcome any suggestions. Thanks.

1
  • thanks guypursey! and mariozski here, I want to change the src attribute of audio-tag by using the javascript. In javascript i am selecting the audio sound track that track i want to play in HTML audio-tag. Thanks for help guys. Commented Mar 13, 2013 at 13:16

2 Answers 2

1

Instead of creating a tag why don't you just create an object Audio and do something like this :

var som = new Audio();
som.src = "powerup.mp3";
som.load();

and after audio.readyState >= audio.HAVE_CURRENT_DATA you can call som.play();

This is a sample that wrote some time ago for a game framework : https://github.com/hamilton-lima/vaca5/blob/master/lib/audio.js

Sign up to request clarification or add additional context in comments.

2 Comments

hamilton I looked your code, it's nice & for game purpose. I tried your suggestion but it won't work & couldn't fetch the selected file input to the <audio> tag source dynamically by using js.
I wasn't able to use the the <audio> tag neither ... only worked for me create the audio object, using new Audio().
1

I'm not exactly sure if I understand what you're trying to achieve. But to set source for audio you do as you've posted:

var element = document.getElementById('audio');
if (element.canPlayType('audio/wav')) {
  element.src = "link";
} else if (element.canPlayType('audio/mpeg')) {
  element.src = "link";
} else {
   alert('Your browser does not support wav/mpeg audio.');
}

Is it not working? What's exactly the problem? Maybe prepare some fiddle to get closer look what are you trying to achieve.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.