Using Javascript to play an audioelement (html5) - javascript

I'm trying to figure out how to trigger playing an audio from javascript. I got some html which looks like:
<div class='audio' >foo
<audio preload='auto' controls src='test.wav'>
<b>Your browser does not support the audio tag.</b>
</audio>
</div>
And I'm trying to trigger it with:
$(document).ready(function () {
$('.audio').each(function(){
var audio = $(this).find('audio').get();
$(this).click(function(){
audio.volume = 100;
alert('1 '+audio);
audio.play();
alert('2');
});
});
});
alert('1 '+audio); works as expected and reports audio as HTMLAudioElement. However alert('2'); is not called because I get the error 'audio.play' is not a function. What can I do to solve this problem?

Your code looks perfect. What is the error you are getting is it "alert.play" is not a function or "audio.play" is not a function.
I think
var audio = $(this).find('audio').get();
returns an array try this
var audio = $(this).find('audio').get(0);

Controlling audio without jQuery using just JavaScript is even easier if you give the audio tag an ID:
<audio id="myAudioTagID" type="audio/mpeg" src="sound.mp3"></audio>
then you can simply get the element and apply .pause(), .start(), stop() :
var audio = document.getElementById("myAudioTagID");
audio.play();
audio.pause();
audio.stop();

Related

Stop embedded Javascript song from autplaying on Chrome?

I have the following line:
<embed src="/sounds/move.wav" autostart="0" width=0 height=0 id="move_sound" enablejavascript=true>
Which autoplays the song on Chrome regardless of any parameters I play with (autoplay, etc.).
Anyone know how to stop it from playing?
EDIT: Not the same as the above, I'm dealing only with embed tags and not video tags.
Try using an audio tag:
<audio src="/sounds/move.wav">
Your browser does not support the <code>audio</code> element.
</audio>
This tag will not autoplay the sound.
You could set src to empty string
var embed = document.getElementById("move_sound");
var audio = embed.src; // save `src`
embed.src = "";
Not really sure but maybe you could stop the audio from playing. with a function you call everytime you switch the src?
http://www.w3schools.com/tags/av_prop_currenttime.asp
Like this?
function start(){
var embed = document.getElementById("move_sound");
//load the video etc.
embed.currentTime = 0;
embed.pause();
}
function playPause() {
if (embed.paused)
embed.play();
else
embed.pause();
}

How to use the selected audio file using javascript, via <audio> tag in HTML 5?

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.
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
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.

Play sound when click on EventListner javascript

Im trying to run a sound when clicking on a dynamically created
But i get the error Object has no method. The tutorials i have found only call elementById
but since this is a class im using the eventlistner.
This is what i have for now.
function AddEvent(){
var addClass= document.getElementsByClassName("add");
addClass=addClass[addClass.length-1];
addClass.addEventListener("click", playsound, true);
function playsound() {
var mySound = src="wav/add.wav"
mySound.play();
}
}
You can create an audio element in HTML 5, hide it, and then use JavaScript / jQuery to manipulate it. So your HTML would look something like:
<audio id="mySound">
<source src="add.ogg" type="audio/ogg">
<source src="add.mp3" type="audio/mpeg">
</audio>
And then you can use the following JS:
function AddEvent()
{
var addClass = document.getElementsByClassName("add");
addClass = addClass[addClass.length-1];
addClass.addEventListener("click", function() {
document.getElementById('mySound').play();
}, true);
}
You can see a working jsFiddle here. You should be advised that this uses HTML 5 though, so IE < 9 won't support this.

HTML5 audio ended function [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
HTML5 audio element with dynamic source
I'm trying to get the player to reload a new track once the current one ends, but I think I might have done something wrong.
This is the player:
<audio id="audio" autoplay controls="controls" onclick="start()">
<source src="song.php" type="audio/mpeg" />
</audio>
Here's the script:
function start(){
var audio = document.getElementById('audio');
audio.play();
audio.addEventListener('ended',function(){
$.post("song.php", function(result){
audio.src = result;
audio.pause();
audio.load();
audio.play();
});
});
}
If I change the script to this, it works...but I don't want to reload the whole page:
function start(){
var audio = document.getElementById('audio');
audio.play();
audio.addEventListener('ended',function(){
window.location = 'player.html';
});
}
For starters, you are attaching a new event handler every single time the element is clicked. If someone frequently pauses the music, they will run into problems.
Intead, try this:
<audio id="audio" autoplay controls src="song.php" type="audio/mpeg"></audio>
<script type="text/javascript">
document.getElementById('audio').addEventListener("ended",function() {
this.src = "song.php?nocache="+new Date().getTime();
this.play();
});
</script>
I'm assuming that song.php is a PHP file that returns the audio data. The nocache query parameter will ensure that the file is actually called every time.

Loading Audio Element After Dynamically Changing the Source

I have a couple of audio elements that appear in the body of my page. They look like this.
<audio id="sound1" preload="auto">
<source id="sound1source" src="../../Content/Audio/gau.mp3">
//add .ogg here later
</audio>
<audio id="sound2" preload="auto">
<source id="sound2source" src="../../Content/Audio/mah.mp3">
//add .ogg here later
</audio>
The audio plays when a user mouses over certain divs. Here's the code that triggers it.
var audio = $("#sound1")[0];
$("#ChoiceA").mouseenter(function () {
audio.play();
});
var audio2 = $("#sound2")[0];
$("#ChoiceB").mouseenter(function () {
audio2.play();
});
Everything above works fine. My problem occurs when I attempt to dynamically change the source element after making an ajax call. Here's my javascript that accomplishes that.
var src1 = "../../Content/Audio/" + data.nouns[0].Audio1 + ".mp3";
var src2 = "../../Content/Audio/" + data.nouns[1].Audio1 + ".mp3";
$("#sound1source").attr("src", src1);
$("#sound2source").attr("src", src2);
When I inspect the page after triggering the ajax call to change the source path for the audio elements, I see that the source is updated. No problem there. The problem is that the audio that the new paths point to does not play.
After hunting around I found this note on w3.org "Dynamically modifying a source element and its attribute when the element is already inserted in a video or audio element will have no effect. To change what is playing, either just use the src attribute on the media element directly, or call the load() method on the media element after manipulating the source elements."
The comment on w3.org seems to be related so I tried calling $('#sound1').load() and also $('#sound1source').load(). Neither solved my problem.
Can someone tell me what I've done wrong? If I need to cause the audio element to load again after dynamically changing the src, how do I do that?
-------------UPDATE-------------
Based on Swatkins suggestion I created the following function to create the audio tag when the user mouses over the target div. Unfortunately this has not solved the problem either.
function attachAudio1(src) {
$('#audio1').remove();
var audio = $('<audio>');
audio.attr("src", src);
audio.attr("id", "audio1");
audio.appendTo('body');
attachPlayAction();
};
function attachPlayAction() {
var audio = $("#audio1")[0];
$('#ChoiceA').live('mouseenter', function () {
audio.play();
});
};
You should call load like this:
var audio = $("#sound1")[0];
$("#ChoiceA").mouseenter(function () {
audio.load();
audio.play();
});
var audio2 = $("#sound2")[0];
$("#ChoiceB").mouseenter(function () {
audio.load();
audio2.play();
});
Have not tested doing it like above, but have testet this previously with a seperate function looking something like this:
<audio id="sound1" preload="auto" src="../../Content/Audio/gau.mp3">
function changeAudio(){
audio = document.getElementById("sound1");
audio.src = "../../Content/Audio/" + data.nouns[0].Audio1 + ".mp3";
audio.load();
audio.play();
}
$("#ChoiceA").mouseenter(function () {
changeAudio();
});
and that worked fine for me?
EDIT: Adding a fiddle, maybe that will help you figure this out?
http://jsfiddle.net/Z3VrV/
This is tricky. I would try replacing the whole <audio> element instead of just changing its source. This way, the new audio element hasn't been added to the page, so it will be forced to load the file.
load() followed by play() right away leads to trouble. Trying listening for the canplay event before attempting to play the audio as suggested in https://stackoverflow.com/a/8705478/1374208

Categories