Play sound when click on EventListner javascript - 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.

Related

JQuery play/pause on HTML5 video is slow

I have an HTML5 video that I want to play/pause when you click anywhere on the video. The code I wrote below works, but if I click the video a few times it starts to get slow and will even freeze sometimes. I saved the selectors in variables hoping that would take care of the issue, but it hasn't made a noticeable difference. Is there a bug in my code that I'm not seeing and the console isn't detecting? Or is there just a better way to write this so it isn't so slow? By the way, the intro-vid ID is on the <video> element in the HTML.
var $video = $('video')[0];
var $introVid = $('#intro-vid');
// If the video is playing, pause it when clicked
$introVid.on('play', function() {
$introVid.click(function() {
$video.pause();
});
});
// If the video is paused, play it when clicked
$introVid.on('pause', function() {
$introVid.click(function() {
$video.play();
});
});
EDIT: Here is the HTML
<video id="intro-vid" controls>
<source src="placeholder.mp4" type="video/mp4">
<source src="placeholder.webm" type="video/webm">
Your browser does not support the video tag.
</video>
You should not bind event handlers inside of other handlers, this way them quickly multiply causing troubles. Try this instead:
var $video = $('video')[0];
var $introVid = $('#intro-vid');
$introVid.click(function () {
$video.paused ? $video.play() : $video.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.

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

Using Javascript to play an audioelement (html5)

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();

Jquery return original event on video

I have multiple video plays on a single page which I need to listen for onplay and onpause triggers, and execute custom functions which take the IDs from each of the videos tags. I need to be able to get the video id that was activated. Ive tried a few different ways, with the simple vid.onplay event works well when I know what ID is being called into. I've tried the $("video").onplay but doesn't seem to be working.
jQuery( document ).ready(function($) {
$("video").onplay = function() {
alert("The video has been paused");
};
var vid = document.getElementbyid("myVideo");
vid.onplay = function() {
alert("The video has been played");
};
});
<video class="mdia_video_player" id=myVideo poster="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.jpg?336660464" id="v0" onclick="doplayvideo(" 0")"="" controls="">
<source src="https://tcokchallenge.com/launch2/wp-content/uploads/2020/04/Carter.mp4?1222152426" type="video/mp4">
</video>```
In your first demo, it should be $("#video") to call by ID. It also says .onplay and then says that is was paused so you might want to fix that.
Ended up doing a much simpler answer, videos are within a php loop. So, I placed this within the tag
onpause="dopausevideo(<?=$vid ?>)"
onplay="doplayvideo(<?=$vid ?>)"

Categories