Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

audio.play() is not a function.

I am doing this Javascript (vanilla JS) 30 days challenge by http://wesbos.com. and im trying not to look at the reference code for the first challenge.

Any way, I am trying to make this code work, but i eventually get this error : " Uncaught TypeError: audElem.play is not a function "

This is my code :

function functionA( item){

  //  alert("HEYYY")
  item.classList.add("playing");

  var audElem= item.getElementsByTagName('audio') [0].getElementsByTagName('source')[0];

  var song= audElem.getAttribute('src');
  song.currentTime=0;
  song.play();
}

And this the html part:

<li class="flex-item " > A  

  <span class="flex-SubItem"> <br />  BOOM </span> 

  <audio id="boom" >
   <source src="sound-effects/boom.mp3" type="audio/mpeg">
  </audio>
</li>

I tried to figured it out but nothing. I have no one to ask but you guys. I hope i get answers. thank any way :)

like image 435
olfa Dhaouadi Avatar asked Jan 20 '17 15:01

olfa Dhaouadi


People also ask

How you can use JavaScript to play the sound for the button Colour selected?

Hello everyone, In this post, we will examine how to solve the How You Can Use Javascript To Play The Sound For The Button Color Selected problem using the computer language. var audio = new Audio("play. mp3"); audio. play();


3 Answers

play is a method of the <audio> object but you are calling it on a string that you get from an attribute of the <source> object.

like image 99
Quentin Avatar answered Nov 14 '22 21:11

Quentin


For who ever is interested i finally managed to make it work by getting the id of the audio tag and call it after that. here's the code:

             function functionA( item){

             item.classList.add("playing");

            var audElem= item.getElementsByTagName('audio')[0].getAttribute('id');

             var song = document.getElementById(audElem);
             song.play();

         } 
like image 42
olfa Dhaouadi Avatar answered Nov 14 '22 21:11

olfa Dhaouadi


I had the same problem and just fixed it using querySelector. In your case, you can replace the code below:

var audElem= item.getElementsByTagName('audio') [0].getElementsByTagName('source')[0];
var song= audElem.getAttribute('src');

with this single line here:

document.querySelector('boom').play();
like image 38
aguiarroney Avatar answered Nov 14 '22 22:11

aguiarroney