How to mute/unmute sound of an audio using javascript - javascript

I have created a fiddle of my function here( http://jsfiddle.net/rhy5K/10/ ) . Now i want to provide the Sound "Mute/unpute" option for users. Example if i click on "a link then sound playing like Get ready,5,4,3,2,1 should be mute and vice-versa.
I am thinking like to call a to toggle_sound function on click, but i am confuse like what should i write inside the function to mute the sound.
Please provide me a logic, or a solution for my problem.
Explanation using code example:
I want to MUTE/UnMUTE this below sound playing
var playGetReady = function (done) {
var ids = ['audiosource', 'a_5', 'a_4', 'a_3', 'a_2', 'a_1'],
playNext = function () {
var id = ids.shift();
document.getElementById(id).play();
if (ids.length) {
setTimeout(playNext, 1000);
} else {
done();
}
};
playNext();
};
Warning: This JS fiddle demo may play sound on load

Try
HTML5 Video_tag for display video with audio
or
this below example along with html5 with jquery
window.my_mute = false;
$('#my_mute_button').bind('click', function(){
$('audio,video').each(function(){
if (!my_mute ) {
if( !$(this).paused ) {
$(this).data('muted',true); //Store elements muted by the button.
$(this).pause(); // or .muted=true to keep playing muted
}
} else {
if( $(this).data('muted') ) {
$(this).data('muted',false);
$(this).play(); // or .muted=false
}
}
});
my_mute = !my_mute;
});

I think you can use:
document.getElementById(id).volume = 1;
or
document.getElementById(id).volume = 0;

Related

Javascript Play Video on Mouse Hover (Multiple Videos)

I have the following JavaScript code that work great when I hover over a video. I like how the start and stop is broken into functions and it allows me to customize the hover play exactly how I want. However, this code only works on the first video on the page and I have several videos that are loaded on the page dynamically.
I would like to modify this code so that it will work on all videos on the page. I'm thinking that maybe the functions need to be called inside a loop? I'm not sure as I do not know JavaScript well, so any help on how to modify this code would would be much appreciated!
const video = document.querySelector("video");
function startPreview() {
video.muted = true;
video.currentTime = 5;
video.playbackRate = 2.5;
video.play();
}
function stopPreview() {
video.currentTime = 5;
video.playbackRate = 1;
video.pause();
}
let previewTimeout = null;
video.addEventListener("mouseenter", () => {
startPreview();
previewTimeout = setTimeout(stopPreview, 3000);
});
video.addEventListener("mouseleave", () => {
clearTimeout(previewTimeout);
previewTimeout = null;
stopPreview();
});
You can do event delegation to handle all videos. So:
document.body.addEventListener('mouseenter', (event) => {
if (event.target.matches('video') {
// start playing
}
});
More on the matches() method on MDN.
You would also modify the start and stop methods to take the video element as a parameter:
function startPreview(video) {
video.muted = true;
video.currentTime = 5;
video.playbackRate = 2.5;
video.play();
}
And pass them the event.target.

A-Frame - playing / pausing sound with a custom ('a-sound') source

Edit 2: Here is the working code. Many thanks to Piotr for his help I couldn't have done it so effortlessly without you guys.
sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3});
let playing = false;
var el = document.querySelector('a-box');
let audioEl = document.querySelector("a-sound");
var audio = audioEl.components.sound;
el.addEventListener('click', () => {
if (!playing) {
audio.playSound();
} else {
audio.stopSound();
}
playing = !playing;
})
} );
request.send( null );
}
});
Edit: I've got the sound playing from a dynamic URL (in my JSON file), but I cant seem to get the event listener function right (for playing / pausing on click).
sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3});
let audioEl = document.querySelector("a-sound");
let audio = audioEl.components.sound;
sceneEl.querySelector('a-box').addEventListener('click', function () {
if(!playing) {
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}
playing = !playing;
});
} );
request.send( null );
}
});
Original: I'm using this component in A-Frame, but I'm looking to play the sound from the src in the ('a-sound') entity rather than from the asset link. The reason is because I'm loading the sound files dynamically from a JSON array so they don't exist in any list of assets. I've got all my files loading but am having trouble getting this component to hook into my loaded sceneEl.querySelector('a-sound').setAttribute('sound', {src:url3}); code. I'm thinking its just a small syntax issue but I'm not 100% sure. Could someone please look over this for a minute and tell me if its doable? This is the code (same as the link except for the (a-sound) within the querySelector.
AFRAME.registerComponent('audiohandler', {
init:function() {
let playing = false;
let audio = document.querySelector('a-sound');
this.el.addEventListener('click', () => {
if(!playing) {
audio.play();
} else {
audio.pause();
audio.currentTime = 0;
}
playing = !playing;
});
}
})
</script>
Using the <a-sound> You must handle things a bit differently.
playing / stopping the sound should be done within the sound component. You need to access it via yourEntityName.components.sound and use the playSound() and stopSound() methods.
check it out on my glitch. I set the source via the setAttribute(), and make a play / stop button.
My <a-sound> has a geometry to be a button, but You can make a <a-sound> entity, and use it like this:
let audioEl = document.querySelector("a-sound");
audioEl.setAttribute("src", "sourceURL");
let audio = audioEl.components.sound;
// play = audio.playSound();
// stop = audio.stopSound():
Furthermore, there are many issues with the nodes not being fully loaded. Check out this example:
<a-entity component></a-entity>
<a-sound></a-sound>
If the component tries to grab a reference to the document.querySelector("a-sound").components.sound, it may be undefined. If so, You should try to wait until it emits the loaded signal.

Check if a HTML5 video is playing using jquery

I've written a small jquery code to override HTML 5 play function. However, I am not able to check if a video is playing or not.
Here is my jquery code
$("video").click(function() {
var video = $("#myvideo").get(0);
video.play();
$(".play").css("display", "none");
return false;
});
$("#myvideo").bind("pause ended", function() {
$(".play").css("display", "block");
});
Just give me simple tips to show a div with class="pause"(I have CSS for it) when the video is paused and pause the video as well.
You'd use the paused property to check if the video is paused.
If it's not paused, it's playing
$("video").click(function() {
var video = $("#myvideo").get(0);
if ( video.paused ) {
video.play();
$(".play").hide();
$(".pause").show();
} else {
video.pause();
$(".play").show();
$(".pause").hide();
}
return false;
});
As Jquery is the framework of Javascript
you can use the following code (involves Video JS Frame work):
var my_video_id = videojs('video_id');
if (my_video_id.player_.paused()) {
my_video_id.player_.play();
} else {
my_video_id.player_.pause();
}

Stopping/Pausing audio when another audio file is clicking using jQuery

I have created a site with image thumbnails of people I have photographed. When a visitor clicks on one of the thumbnails the full image is revealed using jQuery, and an audio introduction plays. I have a different audio introduction for each thumbnail/image combination - 15 at present with more being added daily.
I would like to ensure that if a visitor clicks on another thumbnail before the previous audio file has completed, that the previous audio file is stopped/paused to allow the new audio file to be played - thereby ensuring two or more tracks do not play simultaneously.
I am currently using the following snippet of code, wrapped in an anonymous function, to play each audio file individually when the appropriate thumbnail is clicked - so this snippet is duplicated for each audio file, but don't know how to ensure they do not play over one another.
$(".bridget-strevens").click(function(){
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused){
audio.play();
} else {
audio.pause();
}
});
Any help you could give me would be very grateful, as I am just starting to learn jQuery, and don't have the knowledge to come up with a workable solution.
Thanks in advance for your help!
Add a .audio class to all your audio elements and loop through all of them when an audio is clicked.
$(".bridget-strevens").click(function () {
$('.audio').each(function (index, value) {
if (!value.paused) {
value.pause();
}
});
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
});
If that seems too heavy for you then simply add the audio element in a global variable such as:
var currentAudio;
Then when a new audio is clicked, simply pause that one, play the new one and update the currentAudio variable with the new element currently being played.
var currentAudio = null;
$(".bridget-strevens").click(function () {
if(currentAudio != null && !currentAudio.paused){
currentAudio.pause();
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
Update:
Thanks for the prompt responses! Grimbode, I've tried what you
suggest, and that seems to work. However is there the ability to stop
and reset rather than just pause - so if they clicked on 1 then [2]
before 1 finished, then clicked 1 again, that 1 would start from
the beginning again rather than the point at which it was paused? And
is there any way of check the state 'globally', and then add code for
each individual audio file - just to keep the amount of code and
duplication down? Thanks again!! –
Yes. Play audio and restart it onclick explains in detail how to do this. The final result would look something like this:
var currentAudio = null;
$(".bridget-strevens").click(function () {
if(currentAudio != null && !currentAudio.paused && currentAudio != this){
currentAudio.pause();
//Here we reset the audio and put it back to 0.
currentAudio.currentTime = 0;
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
You can't really optimize the code much more. You're going to have apply the click event on every audio element. You're going to have to keep the current playing audio element memorized so you don't have to loop through all the audio files.
If you really want to take this further you could create a library to handle everything. Here is an example:
(function(){
var _ = function(o){
if(!(this instanceof _)){
return new _(o);
}
if(typeof o === 'undefined'){
o = {};
}
//here you set attributes
this.targets = o.targets || {};
this.current = o.current || null;
};
//create fn shortcut
_.fn = _.prototype = {
init: function(){}
}
//Here you create your methods
_.fn.load = function(){
//here you load all the files in your this.targets.. meaning you load the source
//OR you add the click events on them.
//returning this for chainability
return this
};
//exporting
window._ = _;
})();
//here is how you use it
_({
targets: $('.audio')
}).load();

How to create a play sound function

Sometimes when an error is detected I want my page to play a sound.
I made this javascript, it does not work:
function playsound(){
var obj = document.createElement("audio");
obj.setAttribute("src", "click.mp3");
obj.play();
}
if($('#noerrors').css('display') != 'none' ) {
playsound();
}
Why not?
I want to call playsound(); whenever it please me.
When using:
if($('#noerrors').css('display') != 'none' ) {
var obj = document.createElement("audio");
obj.setAttribute("src", "click.mp3");
obj.play();
}
It works fine. What's the problem of the first script?
http://jsfiddle.net/3Camg/
<div id="error_sound"></div>
<span class="click">Test Sound by clicking here</span>
function play_sound()
{
$('#error_sound').html('<audio src="http://www.intriguing.com/mp/_sounds/hg/dead.wav" id="err_player"></audio>');
document.getElementById('err_player').play();
}
$('.click').bind('click',play_sound);
You cannot call play on jQuery element, but the HTML element that underlies it.
Can I suggest you another solution?
Define <audio> just once at the beginning, then call play() by selecting that tag:
1.Insert this whenever you want, at the end of the <body> for example.
<audio id="myAudio" src="click.mp3"></audio>
2.Then if you have an error, play it or pause otherwise:
if($('#noerrors').css('display') != 'none' ) {
document.getElementById("myAudio").play();
} else {
document.getElementById("myAudio").pause();
document.getElementById("myAudio").currentTime = 0;
}
I suggest this solution (DEMO):
function playsound(){
var $audioElement = $("<audio id='audioId'/>");
$audioElement.attr('src', "click.mp3");
$audioElement[0].load();
$audioElement[0].play();
}
if($('#noerrors').css('display') != 'none' ) {
playsound();
}
To ensure to play after load:
$audioElement.on('canplay canplaythrough', function(){
$audioElement[0].play();
});

Categories

Resources