Paul
Paul

Reputation: 1327

myAudio.play() is not a function

I am getting a strange message when I try to play an audio file.

On my html I got a sound file:

<audio id="song" src="song.mp3"></audio>

and when I click an image:

<img onclick="togglePlay()" src="image.png" width="100%">
                    </div>

on my JavaScript:

  var myAudio = $("#song");

  var isPlaying = false;
  function togglePlay() {
     if (isPlaying) {
          myAudio.pause();
      } else {
        myAudio.play();
      }
   };
   myAudio.onplaying = function() {
      isPlaying = true;
   };
   myAudio.onpause = function() {
      isPlaying = false;
   };

I am getting no sound and on the console a warning with the message: "myAudio.play() is not a funtion".

Upvotes: 2

Views: 7907

Answers (1)

Philip Kirkbride
Philip Kirkbride

Reputation: 22879

Example solution based on your question:

var myAudio = $("#song")[0];

var isPlaying = false;

function togglePlay() {
    if (isPlaying) {
        myAudio.pause();
    } else {
        myAudio.play();
    }
};
myAudio.onplaying = function() {
    isPlaying = true;
};
myAudio.onpause = function() {
    isPlaying = false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<audio id="song" src="https://ia801009.us.archive.org/4/items/BeatlesGreatestHits/02%20With%20a%20Little%20Help%20From%20My%20Friends.mp3"></audio>

<img onclick="togglePlay()" src="https://pmcdeadline2.files.wordpress.com/2014/06/the-beatles-1__140613232022.jpg" width="100%">

If broken in future check image and audio for deadlinks.

Upvotes: 5

Related Questions