Play() Causes distortion/echo when playing sound - javascript

I am trying to make a chrome extension. Right now I have these codes:
<button style="text-align:center; margin-bottom: 5px;" id="myboobutton">DogMeme.avi</button>
<script type="text/javascript" src="popup.js"></script>
The html that will be the button that plays a sound
I am making a button and giving it an id so it can call a Javascript file to play a sound (I have to do this because you can't run JS on the HTML of a chrome extension.)
The button has an ID of 'myboobutton'
function myboo() {
var heyboosong = new Audio();
heyboosong.src = "myboo.mp3";
heyboosong.volume=0.5
heyboosong.play();
}
document.getElementById('myboobutton').addEventListener('click', myboo);
The button calls this popup.js so it can play the audio file.
I have a soundboard extension that plays various songs that are mp3s. When they play in the chrome extension they sound echoey. When the individual audio files play they sound fine. I suspect that it is making multiple calls to the function resulting in the echo. I am trying to figure out how to fix it. (thanks Makyen for helping to clarify) I've tested again and it still makes it.
It seems like all mp3 sounds seem to do this. Not sure if it is specific to chrome extensions or not. But it doesn't seem to happen on faster PCs as much. I am new to coding, I have just learned all of this in the past week. Thanks a bunch!
Here is the unpacked extension
https://drive.google.com/drive/folders/0B3AU3p8wyWK3YXo1YUlGWGg5RGs?usp=sharing

You can disable the button in the click event and create a setTimeout() function to enable the button again after a certain period of time.
For example:
var mybooBtn = document.getElementById('myboobutton');
mybooBtn.addEventListener('click', function() {
mybooBtn.disabled = true;
setTimeout(function() {
mybooBtn.disabled = false;
}, 1000);
// code to play sound goes here
});
Here's a fiddle: https://jsfiddle.net/g9wx30qj/

You need to apply the debounce/throttle concept. It is meant to be used when a function needs a delay between executions (i.e. ajax calls in typeahead plugins).
You can use a simple Throttle implementation:
var Throttle = function(fn, time) {
var flag = true, toId;
return function() {
if (flag) {
var args = arguments;
fn.apply(this, args);
flag = false;
clearTimeout(toId);
toId = setTimeout(function() {
flag = true;
}, time);
}
}
};
And then, in your code:
document.getElementById('myboobutton').addEventListener('click', Throttle(myboo,1000)); //1000ms is 1second

Ok,do one thing;(I am showing a solution using jQuery)
$("#myboobutton").click(function(){
$("#myboobutton").css("pointer-events","none"); //click 'll be disabled by this
//write code for playing sound;
setTimeout(function(){
$("#myboobutton").css("pointer-events",""); //button 'll be clickable again after 1 sec
},1000)
})

Related

How do I make sure all resources are loaded before running a function?

I'm working on a music webapp that plays a random sequence of notes, but I ran into this issue: whenever it was the case that I was going to press play for the first time after the page loaded, the sequence would "choke" before getting on track. I thought maybe that was because the resources are not yet loaded when I press play for the very first time. I guess I was right, did some research, found this preload = auto thing, which seemed to solve this problem. At least, if you refresh or visit the page for the first time and press play immediately, it works just fine. However, if you don't do anything for a while, like 2/3 minutes, the same thing happens. There's a delayed start, as if it's loading the file, and then it awkwardly speeds up like it's trying to catch up with the setInterval timer. I wrote this very simplified version of the code just to illustrate:
<button>Play</button>
<audio src="source1.mp3"></audio>
<audio src="source2.mp3"></audio>
<audio src="source3.mp3"></audio>
<script>
let notes = []
document.querySelectorAll("audio").forEach(function(note){
notes.push(note)
})
function play(){
let random_index = Math.floor(Math.random() * 3),
note = notes[random_index]
note.play()
setInterval(function(){
note.pause()
note.currentTime = 0
play()
}, 500)
}
let button = document.querySelector("button")
button.addEventListener("click", function(){
play()
})
</script>
So my question is how do I solve this? Is there anyway to tell the function to hold until it can actually play the first file? Maybe a DOM event that fires when the resource is buffered and ready? I feel like I can't relly let the timer begin until I have a way to check that, otherwise it will go crazy as usual. Any ideas will be greatly appreciated!
The load event is called after the page is fully loaded:
window.addEventListener("load", function(){
// Your code
});
The DOMContentLoaded event is called after the DOM is loaded but before css and img.
document.addEventListener("DOMContentLoaded", function(){
// Your code
});

Please help me to use play/stop code so my code should stop and reset not pause [duplicate]

I am playing a small audio clip on click of each link in my navigation
HTML Code:
<audio tabindex="0" id="beep-one" controls preload="auto" >
<source src="audio/Output 1-2.mp3">
<source src="audio/Output 1-2.ogg">
</audio>
JS code:
$('#links a').click(function(e) {
e.preventDefault();
var beepOne = $("#beep-one")[0];
beepOne.play();
});
It's working fine so far.
Issue is when a sound clip is already running and i click on any link nothing happens.
I tried to stop the already playing sound on click of link, but there is no direct event for that in HTML5's Audio API
I tried following code but it's not working
$.each($('audio'), function () {
$(this).stop();
});
Any suggestions please?
Instead of stop() you could try with:
sound.pause();
sound.currentTime = 0;
This should have the desired effect.
first you have to set an id for your audio element
in your js :
var ply = document.getElementById('player');
var oldSrc = ply.src;// just to remember the old source
ply.src = "";// to stop the player you have to replace the source with nothing
I was having same issue. A stop should stop the stream and onplay go to live if it is a radio. All solutions I saw had a disadvantage:
player.currentTime = 0 keeps downloading the stream.
player.src = '' raise error event
My solution:
var player = document.getElementById('radio');
player.pause();
player.src = player.src;
And the HTML
<audio src="http://radio-stream" id="radio" class="hidden" preload="none"></audio>
Here is my way of doing stop() method:
Somewhere in code:
audioCh1: document.createElement("audio");
and then in stop():
this.audioCh1.pause()
this.audioCh1.src = 'data:audio/wav;base64,UklGRiQAAABXQVZFZm10IBAAAAABAAEAVFYAAFRWAAABAAgAZGF0YQAAAAA=';
In this way we don`t produce additional request, the old one is cancelled and our audio element is in clean state (tested in Chrome and FF) :>
This method works:
audio.pause();
audio.currentTime = 0;
But if you don't want to have to write these two lines of code every time you stop an audio you could do one of two things. The second I think is the more appropriate one and I'm not sure why the "gods of javascript standards" have not made this standard.
First method: create a function and pass the audio
function stopAudio(audio) {
audio.pause();
audio.currentTime = 0;
}
//then using it:
stopAudio(audio);
Second method (favoured): extend the Audio class:
Audio.prototype.stop = function() {
this.pause();
this.currentTime = 0;
};
I have this in a javascript file I called "AudioPlus.js" which I include in my html before any script that will be dealing with audio.
Then you can call the stop function on audio objects:
audio.stop();
FINALLY CHROME ISSUE WITH "canplaythrough":
I have not tested this in all browsers but this is a problem I came across in Chrome. If you try to set currentTime on an audio that has a "canplaythrough" event listener attached to it then you will trigger that event again which can lead to undesirable results.
So the solution, similar to all cases when you have attached an event listener that you really want to make sure it is not triggered again, is to remove the event listener after the first call. Something like this:
//note using jquery to attach the event. You can use plain javascript as well of course.
$(audio).on("canplaythrough", function() {
$(this).off("canplaythrough");
// rest of the code ...
});
BONUS:
Note that you can add even more custom methods to the Audio class (or any native javascript class for that matter).
For example if you wanted a "restart" method that restarted the audio it could look something like:
Audio.prototype.restart= function() {
this.pause();
this.currentTime = 0;
this.play();
};
It doesn't work sometimes in chrome,
sound.pause();
sound.currentTime = 0;
just change like that,
sound.currentTime = 0;
sound.pause();
From my own javascript function to toggle Play/Pause - since I'm handling a radio stream, I wanted it to clear the buffer so that the listener does not end up coming out of sync with the radio station.
function playStream() {
var player = document.getElementById('player');
(player.paused == true) ? toggle(0) : toggle(1);
}
function toggle(state) {
var player = document.getElementById('player');
var link = document.getElementById('radio-link');
var src = "http://192.81.248.91:8159/;";
switch(state) {
case 0:
player.src = src;
player.load();
player.play();
link.innerHTML = 'Pause';
player_state = 1;
break;
case 1:
player.pause();
player.currentTime = 0;
player.src = '';
link.innerHTML = 'Play';
player_state = 0;
break;
}
}
Turns out, just clearing the currentTime doesn't cut it under Chrome, needed to clear the source too and load it back in. Hope this helps.
As a side note and because I was recently using the stop method provided in the accepted answer, according to this link:
https://developer.mozilla.org/en-US/docs/Web/Guide/Events/Media_events
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element. In the link it mentions Firefox, but I encountered this event firing after setting currentTime manually on Chrome. So if you have behavior attached to this event you might end up in an audio loop.
shamangeorge wrote:
by setting currentTime manually one may fire the 'canplaythrough' event on the audio element.
This is indeed what will happen, and pausing will also trigger the pause event, both of which make this technique unsuitable for use as a "stop" method. Moreover, setting the src as suggested by zaki will make the player try to load the current page's URL as a media file (and fail) if autoplay is enabled - setting src to null is not allowed; it will always be treated as a URL. Short of destroying the player object there seems to be no good way of providing a "stop" method, so I would suggest just dropping the dedicated stop button and providing pause and skip back buttons instead - a stop button wouldn't really add any functionality.
This approach is "brute force", but it works assuming using jQuery is "allowed". Surround your "player" <audio></audio> tags with a div (here with an id of "plHolder").
<div id="plHolder">
<audio controls id="player">
...
</audio>
<div>
Then this javascript should work:
function stopAudio() {
var savePlayer = $('#plHolder').html(); // Save player code
$('#player').remove(); // Remove player from DOM
$('#FlHolder').html(savePlayer); // Restore it
}
I was looking for something similar due to making an application that could be used to layer sounds with each other for focus. What I ended up doing was - when selecting a sound, create the audio element with Javascript:
const audio = document.createElement('audio') as HTMLAudioElement;
audio.src = getSoundURL(clickedTrackId);
audio.id = `${clickedTrackId}-audio`;
console.log(audio.id);
audio.volume = 20/100;
audio.load();
audio.play();
Then, append child to document to actually surface the audio element
document.body.appendChild(audio);
Finally, when unselecting audio, you can stop and remove the audio element altogether - this will also stop streaming.
const audio = document.getElementById(`${clickedTrackId}-audio`) as HTMLAudioElement;
audio.pause();
audio.remove();
If you have several audio players on your site and you like to pause all of them:
$('audio').each( function() {
$(this)[0].pause();
});
I believe it would be good to check if the audio is playing state and reset the currentTime property.
if (sound.currentTime !== 0 && (sound.currentTime > 0 && sound.currentTime < sound.duration) {
sound.currentTime = 0;
}
sound.play();
for me that code working fine. (IE10+)
var Wmp = document.getElementById("MediaPlayer");
Wmp.controls.stop();
<object classid="clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6"
standby="Loading áudio..." style="width: 100%; height: 170px" id="MediaPlayer">...
Hope this help.
What I like to do is completely remove the control using Angular2 then it's reloaded when the next song has an audio path:
<audio id="audioplayer" *ngIf="song?.audio_path">
Then when I want to unload it in code I do this:
this.song = Object.assign({},this.song,{audio_path: null});
When the next song is assigned, the control gets completely recreated from scratch:
this.song = this.songOnDeck;
The simple way to get around this error is to catch the error.
audioElement.play() returns a promise, so the following code with a .catch() should suffice manage this issue:
function playSound(sound) {
sfx.pause();
sfx.currentTime = 0;
sfx.src = sound;
sfx.play().catch(e => e);
}
Note: You may want to replace the arrow function with an anonymous function for backward compatibility.
In IE 11 I used combined variant:
player.currentTime = 0;
player.pause();
player.currentTime = 0;
Only 2 times repeat prevents IE from continuing loading media stream after pause() and flooding a disk by that.
What's wrong with simply this?
audio.load()
As stated by the spec and on MDN, respectively:
Playback of any previously playing media resource for this element stops.
Calling load() aborts all ongoing operations involving this media element

Play selected audio while pausing/resetting others

I have two audio elements that play through a button's click event. I've successfully managed to pause one if another is selected but also need to set the paused element back to 0.0 seconds (i.e pause and reset).
I'm aware that Javascript currently doesn't have a stop() method which led assume that this would be done by setting its currentTime to 0. If so I just haven't been able to figure out the best way to incorporate this method in my code.
Right now I'm pausing all audio elements in the latter half of the conditional using $(".audio").trigger("pause"); which doesn't too efficient performance wise. What would be the best way to pause and reset only the previously played audio file and not every one on the page?
http://jsfiddle.net/txrcxfpy/
use below code . check DEMO
$(function() {
$('.track-button').click(function() {
var reSet = $('.track-button').not($(this)).siblings(".audio").get(0);
reSet.pause();
reSet.currentTime = 0;
var $this = $(this),
trackNum = $this.text(),
currentAudio = $this.siblings(".audio"),
audioIsPaused = currentAudio.get(0).paused;
if (audioIsPaused) {
currentAudio.get(0).play();
} else {
currentAudio.get(0).pause();
}
});
});

.stop(), and .pause() don't work where .play() does work

On a .js page in a Visual Studio express ASP.NET solution
why does
window.onload() {
document.getElementById('ambience').play();
}
work(and it does!), but why does
window.onload() {
document.getElementById('ambience').play();
document.getElementById('ambience').stop();
}
NOT stop the music? .pause(); doesn't pause the music either
I also tried:
It does play the music. And I have tried:
window.onload = function() {
var snd = document.getElementById('ambience').play();
var clickmeButton = document.getElementById('playJackpot');
clickmeButton.onclick = playSound;
}
function playSound() {
document.getElementById('ambience').stop();
}
what is the equivalent of .stop() or .pause() if those are not applicable? what set of commands
should I be working with in visual studio in order to get sound to play based on a conditional and then definitively shut off or stop after it has played once, and only once ? The background to this is that I have the play button in a timer control, so that it can operate other features, but each timer tick (and that needs to be set at a fraction of a second) kicks off the play again, so that the sound comes out staccato, because it is starting with every 'tick' of the timer. So, I need to play it, then immediately shut off the sound's ability to play, that is until somebody hits the play button again.

Play (and replay) a sound on safari mobile

I need to play a sound when a new message appears on a website. It works fine on Chrome and Safari but I can't make it work on Safari mobile.
I saw that the sound has to be initialised with a user action so I tried that:
var sound = new Audio('./path/to/my/sound.mp3');
var hasPlayed = false;
$('body').bind('click touchstart', function() {
sound.load();
});
sound.addEventListener('play', function() {
hasPlayed = true;
});
var playSound = function() {
if(hasPlayed) {
sound.currentTime = 0;
}
sound.play();
}
Unfortunately, the sound still don't play. I also tried with the Buzz library, and the issue is the same.
So, the question is : how can I play a sound programmatically on mobile browsers ?
First of all: HTML5 audio support in Mobile Safari on iOS (5.01, 5.1) is rather limited. But I have managed to get some small 'event type' sounds working in my iPad 2 web apps. Since you are talking about only one sound file for your app, you don't have to fall back on audio sprites tricks (i.e. merging multiple MP3's into one MP3 file and changing the play position within the merged file depending on the sound you want to be played).
As you have noticed, you cannot play audio automatically in Mobile Safari, i.e. without the user clicking on some element. Technically speaking, the audio must be played (not loaded) in the same call stack as a click event. But you will probably experience a 0,5 second delay then, when Mobile Safari creates the audio object. Here is a solution to this 'problem':
At the start of your app (while loading/initializing), add a click handler to the HTML document that starts playing your audio file as soon as the user clicks/taps anywhere in the app. This will force Safari to start loading the audio.
Listen for the 'play' event that is triggered when the audio is ready to be played, and immediately pause.
Now start playing the audio (without delay) again when you need it.
Here is some quick JavaScript code:
function initAudio() {
var audio = new Audio('./path/to/my/sound.mp3');
audio.addEventListener('play', function () {
// When the audio is ready to play, immediately pause.
audio.pause();
audio.removeEventListener('play', arguments.callee, false);
}, false);
document.addEventListener('click', function () {
// Start playing audio when the user clicks anywhere on the page,
// to force Mobile Safari to load the audio.
document.removeEventListener('click', arguments.callee, false);
audio.play();
}, false);
}
For those that are coming across this problem and the solution by Jeroen is not working here is a solution that works and ensures the proper scoping is correctly enforced.
Make sure initAudio is called on page load. I.e. in your Init function or for jquery inside the document.ready ($(function(){});)
function initAudio(){
var audio = new Audio('./path/to/my/sound.mp3');
var self = this;
//not sure if you need this, but it's better to be safe
self.audio = audio;
var startAudio = function(){
self.audio.play();
document.removeEventListener("touchstart", self.startAudio, false);
}
self.startAudio = startAudio;
var pauseAudio = function(){
self.audio.pause();
self.audio.removeEventListener("play", self.pauseAudio, false);
}
self.pauseAudio = pauseAudio;
document.addEventListener("touchstart", self.startAudio, false);
self.audio.addEventListener("play", self.pauseAudio, false);
}

Categories