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

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

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.

Chrome background autoplay does not work properly

This is the PHP script I use to add the player:
echo "<audio id='my_audio' src='img/default-sound.mp3'></audio>";
And to play it I use this script:
<script>
window.onload = function() {
if (document.getElementById("my_audio") == null) {
alert("null");
} else {
alert("yay");
document.getElementById("my_audio").play();
}
}
</script>
The alerts is just for testing purpose. The issue is: When opening my page in Internet Explorer or Microsoft Edge, it all runs fine, the alert shows up, and the mp3 file is played once. But when opening with Google Chrome, only the alert shows up. Then, if I spam the page refresh button a few times, suddenly the sound plays. What might be causing this issue?
Read this 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.
enable/disable/set default auto-play settings (and many more)in :
chrome://flags
But it just works on the computer you configured it.

How to autoplay sound at javascript page?

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.

audio tag not working in google chrome

I am trying to stream an audio file in google chrome . The file is hosted at a wildfly server.
Below is the sample code
<html>
<head>
<title>Audio Demo</title>
<script type="text/javascript">
function updateSource(){
var audio = document.getElementById('wavSource');
audio.src = 'https://SERVER_URL:8443/FILE_PATH/FILE_NAME.wav';
var a = document.getElementById('audio');
a.load();
}
</script>
</head>
<body>
<audio id="audio" controls="controls">
<source id="wavSource" src="" type="audio/wav"></source>
Your browser does not support the audio format.
</audio>
<button onclick="updateSource();">Item1</button>
</body>
When the button is clicked, the audio.src is set to the specified file. This sample code works fine in firefox but does not work in google chrome. If I paste the audio file link in a tab, then also nothing happens (not able to play), But I am able to save the file.
On the server side a softlink is created in deployment directory which points to the audio file location.
Some other things that I have noticed is that if I am bundling the audio file in an EAR, then I can access it. Now that the audio file is being generated on the fly in a different location , for which I have created a softlink in deployment directory. In this case I am not able to play it.
Can some one please tell me what is that I am doing wrong?
Thank you
well you code looks fine. I tried it with different audio files and it works. I think issue must be with your audio file or path.
Your sample code works as I checked it with a .wav audio source as you can see below. Check the actual file on your server, that you want to play, whether it's accessible, playable and it's an actual .wav file.
If this doesn't work in your Google Chrome, clear its cache completely, update it, restart your computer and check again. It should work then.
Although please, put your script in the bottom of the body tag:
<html>
<head>
<title>Audio Demo</title>
</head>
<body>
<audio id="audio" controls="controls">
<source id="wavSource" src="" type="audio/wav"></source>
Your browser does not support the audio format.
</audio>
<button onclick="updateSource();">Update Source</button>
<script type="text/javascript">
function updateSource(){
var audio = document.getElementById('wavSource');
audio.src = 'http://www.wavsource.com/snds_2018-06-03_5106726768923853/people/men/about_time.wav';
var a = document.getElementById('audio');
a.load();
}
</script>
</body>
</html>
Source: WavSource.com
I have finally solved the issue. It is related to Wildfly 10.0.0. See this link.
All of your audio your files MUST be named as HTTPS, not HTTP. It's a security issue with Chrome.
For one year I couldn't figure out why my random MP3 play JavaScript code stopped working. It worked on Firefox, but not Chrome or Internet Explorer. I tried everything I read online, but nothing worked. I just needed to add an "s" at the end of each "http" for each audio file in the JavaScript code. I had 3,080 files...lol. My webpage works fine now.
Also, your website must be secure. Even if you have security certificates, they won't work unless you activate them, which you can learn how to do online. You can tell if your website is secure by looking for a little closed lock symbol before each web address above.

Categories

Resources