How to autoplay sound at javascript page? - javascript

I am developing a web system to monitor some values from a database, and I need to play some sound alert when a range of values is received. I've tried a lot of internet samples, but anyone works. The error returned is "uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first". The last try was with the code bellow:
<audio id="myAudio" muted="muted">
<source src="./resources/sound/Alarm.mp3" type="audio/mp3">
</audio>
<script>
alert(){
let x = document.getElementById("myAudio");
if(this.percentIntegral[0]>=70 && this.percentIntegral[0]<=80){
//alert("play");
x.play();
}
}
</script>

Thank you for asking this question, I am also suffered from this issue, You can not autoplay audio because the browser needed some interaction with a user after music will autoplay. It's the security purpose of the browser.
The user didn't interact with the document first. It only works when the user interacts with a browser.
You also can not jquery click into the browser. when the user scrolls up down or clicks to any button then after audio will work.

Related

Autoplay Audio in Loop

i am looking for autoplay an audio in loop without getting blocked by browser.
Code :
<audio id="audio1" src="assest/sound/1.mp3" autoplay="" />
<script>
a = document.getElementById('audio1');
a.onended = function(){setTimeout("a.play()", 1000)}
</script>
My current code working on firefox but in default it is blocked, i have to allow autoplay manually so it can play the audio and in other side in chrome the audio is not even playing.
Edited :
Iframe code :
<iframe src="assest/sound/1.mp3" allow="autoplay" style="display:none" id="iframeAudio">
</iframe>
I have even tried iframe auto play code but it still not working with chrome. iframe code automatically trigger auto download of audio file.
Any solution for this?
WITH HTML
<audio controls autoplay loop hidden>
<source src="assest/sound/1.mp3" type="audio/mpeg">
</audio>
Please have a look at this document to know what is the problem that you're facing: https://developer.mozilla.org/en-US/docs/Web/Media/Autoplay_guide.
As described in the document:
As a general rule, you can assume that media will be allowed to autoplay only if at least one of the following is true:
The audio is muted or its volume is set to 0
The user has interacted with the site (by clicking, tapping, pressing keys, etc.)
If the site has been allowlisted; this may happen either automatically if the browser determines that the user engages with media frequently, or manually through preferences or other user interface features
If the autoplay feature policy is used to grant autoplay support to an and its document.
I think a reasonable way is to let users interact with your site first. Eg:
Show an in-page popup and the user clicks to close it;
Ask users whether they want to listen to music or not;
...
After they interacted with your site, you can run the script to play the audio without browser blocking.

How to play audio without strict limitations on JavaScript?

I'm making a game made of bare JavaScript code and I want to manipulate audio in JavaScript.
Specifically, I want to let the page start playing music when some div element is clicked and when using some function in the JavaScript code.
I know audio tag of HTML5 has a limitation that a music file associated with Audio element cannot be played without user clicking the play button of the audio element, so I cannot do like this:
const audio = document.createElement("audio");
audio.src = "url of source";
audio.play();
//Uncaught (in promise) DOMException: play() failed because
//the user didn't interact with the document first. 
//https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
Chrome's autoplay policies are simple:
Muted autoplay is always allowed.
Autoplay with sound is allowed if:
User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
The user has added the site to their home screen on mobile or installed the PWA on desktop.
Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
But I want to manage audio more freely in order to make a good UI of the game.
To achieve my goal, I think I need to introduce another library or API into the JavaScript code or still use audio tag with some tricky tips.
I'm thinking one of the choices could be Web Audio API.
Could you tell me some advice?
Progress
I tried code like the following and it worked when I clicked a div element with click event handler:
<div id="my-div">play</div>
<audio id="myAudio">
<source src="url of source" type="audio/mpeg">
</audio>
const myAudio = document.getElementById("myAudio");
const btn = document.getElementById("my-div");
btn.addEventListener("click",() => {
myAudio.play();
});
However, when I wrote like the following, it didn't work with the same error even if it didn't seem I broke the autoplay policy:
document.getElementById('my-div').addEventListener('click', () => {
const audio = new Audio('url of source');
audio.play();
});
//Uncaught (in promise) DOMException: play() failed because
//the user didn't interact with the document first. 
//https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
The main difference between two codes above is whether I wrote the url of the audio source file in the audio tag or wrote it in the source tag inside the audio tag. I'm guessing this makes some difference but I don't get what exactly is the problem.
You're correct. You can only be sure that the playback will not be blocked by the autoplay policy if the playback is started in response to a user gesture. A button with a click handler is the classic example but the click handler could be attached to a div as well. Let's say your div has an id called my-div. In that case the following should work.
document.getElementById('my-div').addEventListener('click', () => {
const audio = new Audio('url of source');
audio.play();
});
Using the Web Audio API will not change the autoplay policy. Usually the same rules apply no matter which browser API is used.

Is there a way to auto play audio in React without using an onClick event?

I'm getting this error when trying to play audio within componentDidMount.
'Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first.'
componentDidMount() {
document.getElementById("backgroundMusic").play();
}
<audio id="backgroundMusic">
<source src={url} type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
It works fine with an onclick event. Is there any way to autoPlay audio in React? I thought I could trigger the audio to start by using onMouseOver, but ideally the music would just start without any user interaction.
Autoplay Policy Changes no longer allow autoplay without user interaction first.
Muted autoplay is always allowed.
Autoplay with sound is allowed if:
User has interacted with the domain (click, tap, etc.).
On desktop, the user's Media Engagement Index threshold has been crossed, meaning the user has previously played video with sound.
The user has added the site to their home screen on mobile or installed the PWA on desktop.
Top frames can delegate autoplay permission to their iframes to allow autoplay with sound.
The only way to bypass this would be your mouse movement implementation
The error message you've got is pretty much self-explaining. Most of the modern browsers prevent audio/video autoplay before user interaction with the page. They do so to avoid certain undesired effects for the user (for instance, a user might have maximum audio volume set & auto-playing loud audio might surprise/scare her).
There are certain hacks you can try out, but none is really guaranteed to work cross-browser.
I fixed this by catching the error and play the sound after the first click. In your code, that would be something like this:
componentDidMount() {
document.getElementById("backgroundMusic").play().catch((error) => {
document.addEventListener('click', () => {
document.getElementById("backgroundMusic").play()
}, { once: true } )
}
<audio id="backgroundMusic">
<source src={url} type="audio/mpeg" />
Your browser does not support the audio element.
</audio>
This way, you're compliant with the Autoplay Policy Changes mentioned by Halmond and you stay away from hacky solutions referenced by Igor.

How to play notification audio file in Chrome WebExtension without user gesture?

I'm building a webextension for Google Chrome and I'm trying to implement a function that plays a sound effect to notify the user about updates on the background.js script.
var sound = new Audio(browserContainer.runtime.getURL("audio/not.ogg"));
sound.play();
The problem is that thanks to Chrome's policies, the audio cannot autoplay without some sort of user gesture. I receive the error "Uncaught (in promise) NotAllowedError: play() can only be initiated by a user gesture."
How can I force Chrome to autoplay the notification sound without a user gesture? I know it is possible, because I've seen other extensions do this, like "Checker Plus for Gmail"
You can try adding an audio HTML tag to the background page, like this:
manifest.json
"background":{"page":"background.html"}
background.html
<html>
<body>
<audio id="mysound" preload="auto" src="audio/not.ogg"></audio>
<script src="background.js"></script>
</body>
</html>
background.js
var sound = document.getElementById('mysound');
sound.play()

Autoplay HTML5 audio/video in iOS5

I have an HTML5 web-app that has sound effects. I'm trying to get these effects working in iOS5 and can't for the life of me.
Wondering if anyone has any work-arounds to get JS control of an HTML5 audio/video control in iOS5.
Or even a way to control multiple audio files with one click. As it stands right now, if I have 10 sound effects, I'd need 10 user clicks to get control of all of them, which is absurd!
Absurb, but you have to see it from iPhone or any mobile phone's point of view. It is a mobile phone going over a cellular network with bandwidth limitations, which many people know about from the recent Sprint commercial. They do not want users going over their bandwidth limit because some site is sending their phone a large amount of data without them taking action themselves.
The following is an excerpt from the official Safari Developer Library with more details.
User Control of Downloads Over Cellular Networks
In Safari on iOS (for all devices, including iPad), where the user may
be on a cellular network and be charged per data unit, preload and
autoplay are disabled. No data is loaded until the user initiates it.
This means the JavaScript play() and load() methods are also inactive
until the user initiates playback, unless the play() or load() method
is triggered by user action. In other words, a user-initiated Play
button works, but an onLoad="play()" event does not.
This plays the movie: <input type="button" value="Play" onClick="document.myMovie.play()">
This does nothing on iOS: <body onLoad="document.myMovie.play()">
Due to Apple, they have restricted the auto-play features to prevent cell data charges. In xcode4 i added a workaround though. In your "webViewDidFinishLoad" Send a javascript call to auto play the video and it works. I tried this in the html file with regular javascript but it did not work. Doing it through webViewDidFinishLoad did the trick though. In this example i want to auto play the video on my index.html page. I have a javascript function on that page called startVideo().
- (void)webViewDidFinishLoad:(UIWebView *)webView{
NSURLRequest* request = [webView request];
NSString *page = [request.URL lastPathComponent];
if ([page isEqualToString:#"index.html"]){
NSString *js = #"startVideo();";
[myWebMain stringByEvaluatingJavaScriptFromString:js];
}
}
And here's my javascript function:
<script>
function startVideo(){
var pElement3 = document.getElementById('myVideo');
pElement3.play();
}
</script>
And here's the html in case you're new to html video
<video id="myVideo" poster="index_poster.png" width="1024" height="768" xcontrols autoplay="autoplay">
<source src="flow.m4v" type="video/mp4"/>
browser not supports the video
</video>
Have you tried something like this??
function clickedOnce(){
$('audio').each(function(){
this.play();
});
}

Categories

Resources