Trickster
Trickster

Reputation: 57

Sound element not playong when the key is pressed

I have a code which I want to make play a certain sound when the spacebar is pressed;

The window.onload function is the major function that hosts everything within it (it is much bigger but for this, I am using just a small bit)

var mySound;
mySound = "pew.mp3";
window.onload = function () {
   if (keysDown[spacebar] && reload > 30) {
  shootBullet();
  reload = 0;
  mySound.play();
}

I get an error message from the console saying that

main.js:215 Uncaught TypeError: mySound.play is not a function
    at run (main.js:215)
    at loop (main.js:313)

Upvotes: 0

Views: 23

Answers (2)

Pascal
Pascal

Reputation: 128

This error occures because you try to play a string. Actually you can't do that. Something like that might work four you.

var audio = new Audio('audio_file.mp3');
audio.play();

For further details take a look here: Playing audio with JavaScript?

Upvotes: 1

gregooroo
gregooroo

Reputation: 168

You need to wrap string "pew.mp3" with Audio constructor to have access to .play() method

mySound = new Audio("pew.mp3")

https://developer.mozilla.org/en-US/docs/Web/API/HTMLAudioElement

Upvotes: 1

Related Questions