How to play audio in extension?

AudioObj = new Audio; 

will return "Sound is not defined"

I also tried the classic fix:

 var audio = require("audio"); 

but no luck. I could add audio playback in some other part of the extension than in main.js , for example, some kind of content script where it works, but maybe there is a simpler and more elegant solution.

+5
javascript html5-audio firefox-addon firefox-addon-sdk
source share
3 answers

new Audio creates a new <audio> HTML element - this only works in the context associated with the document. SDK modules run in context, but do not have a document, so no DOM methods will work, including this one. The workaround will load about:blank through the page-worker module and enter the contents of the script there. You can then send messages to this content script and let it play audio for you when you need it.

An alternative would be to use nsISound.play() , something like these lines:

 var {Cc, Ci} = require("chrome"); var sound = Cc["@mozilla.org/sound;1"].createInstance(Ci.nsISound); var uri = Cc["@mozilla.org/network/io-service;1"] .getService(Ci.nsIIOService) .newURI(self.data.url(...), null, null); sound.play(uri); 

Please note that nsISound may be out of date soon. This is an old API that is inferior to HTML5 sound.

+6
source share
 var window = require("sdk/window/utils").getMostRecentBrowserWindow(); AudioObj = new window.Audio; 
+4
source share

main.js does not have access to the DOM APIs that usually exist in web content. If you want to use the DOM apis, you need to use content scripts. For more information on how the SDK module works, see the docs:

https://addons.mozilla.org/en-US/developers/docs/sdk/1.7/dev-guide/guides/commonjs.html

+1
source share

All Articles