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".
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".
Share Improve this question edited Nov 1, 2016 at 3:13 user6646201 asked Nov 1, 2016 at 2:35 PaulPaul 1,3477 gold badges30 silver badges60 bronze badges 3-
var myAudio = $("#song");
- returns a jQueery object, not an HTML Element ... jQueery knows nothing of "play" ... either usevar myAudio = document.getElementByID('song');
- or, if you are determined to use jQueery for such a simple task, usevar myAudio = $("#song")[0];
so that myAudio has the one and only audio tag with that ID – Jaromanda X Commented Nov 1, 2016 at 2:37 - thanks for this. Now it's telling me document.getElementByID is not a function!! – Paul Commented Nov 1, 2016 at 2:45
-
because of my deliberate mistake -
document.getElementById
is the real function you are lookng for – Jaromanda X Commented Nov 1, 2016 at 2:55
1 Answer
Reset to default 5Example 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./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<audio id="song" src="https://ia801009.us.archive/4/items/BeatlesGreatestHits/02%20With%20a%20Little%20Help%20From%20My%20Friends.mp3"></audio>
<img onclick="togglePlay()" src="https://pmcdeadline2.files.wordpress./2014/06/the-beatles-1__140613232022.jpg" width="100%">
If broken in future check image and audio for deadlinks.