How can i play sound in a chrome extension [duplicate]

I would like to play sound in 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 it does not work. I did not add anything more, so there are 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 button to site in myscript.js file, this button works well, but i can't play 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();

Answers:

Answer

The easiest way to play some sound/music using JavaScript is by using an Audio object: you just need to have the file you want to play inside your extension 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 anywhere else that is not under a chrome://extension URL) you'll have to declare the audio file in the web_accessible_resources manifest field:

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

Working example

You can download a test extension I made from HERE. It plays a sound through a content script when you click anything inside a stackoverflow.com page.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.