How can I play sound in Chrome extension

I would like to play the sound in a chrome extension. How can I do it? What should I write in myscript.js file?

I tried to write in myscript.js:

var audio = new Audio("alarm.wav"); audio.play(); 

and

 document.write('<audio id="player" src="alarm.wav" >'); document.getElementById('player').play(); 

but that will not work. I didn’t add anything else, so there were no unfulfilled conditions.

My manifest.json file:

 { "name": "Alarm", "version": "1.0.0", "icons": {"64": "icon64.png"}, "permissions": [ "http://site1/", "http://site2/" ], "content_scripts": [ { "matches": ["http://site1/", "http://site2/"], "js": ["myscript.js"], "run_at": "document_end" } ], "manifest_version": 2 } 

If I add a button to the site in the myscript.js file, this button works well, but I can’t play the sound. My audio file is mp3 and is in the same folder as manifest.json and myscript.js, and my myscript.js is:

 var myAudio = new Audio(); myAudio.src = "alarm.mp3"; myAudio.play(); 
+9
javascript google-chrome google-chrome-extension
source share
1 answer

The easiest way to play sound / music using JavaScript is to use the Audio object: you just need to have the file you want to play inside the extensions folder, and you can play it like this:

 var myAudio = new Audio(chrome.runtime.getURL("path/to/file.mp3")); myAudio.play(); 

You can play using play() and pause using pause() .

Remember that if you want to play the sound in a content script (or in another place that is not under the chrome://extension URL), you need to declare the audio file in the web_accessible_resources manifest of the web_accessible_resources manifest:

 "web_accessible_resources": [ "path/to/file.mp3" ] 

Working example

You can download the test extension that I did HERE . It plays the sound through the content script when you click something on the stackoverflow.com page.

+5
source share

All Articles