答案 0 :(得分:2)
我从2016年得到答案;)
该代码不适用于多进程Firefox(将于2016年发布):
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = new window.Audio('http://example.com/audio.mp3');
vaudio.play();
因为sdk/window/utils
。要理解为什么阅读此topic on MDN。
解决方案是page-worker
:
<强> main.js:强>
var pageWorkers = require("sdk/page-worker");
var audioWorker = pageWorkers.Page({
contentURL: './blank.html', //blank html file in `data` directory
contentScriptFile: './worker.js'
});
// for example i want to play song from url
var url = 'http://some-url.com/some-song.mp3';
// send msg to worker to play this url
audioWorker.port.emit('play', url);
<强> worker.js 强>
var audio = new window.Audio;
self.port.on('play', function(url) {
audio.src = url;
audio.play();
});
它适用于我的扩展程序,可以使用新的多进程Firefox版本。
答案 1 :(得分:1)
@Noitidart未来即将到来,2015年您可以编写更少的代码!
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = new window.Audio('http://example.com/audio.mp3');
audio.play();
答案 2 :(得分:0)
这对我有用我不知道2015年是怎样的,但我几个月前写的是:
Cu.import('resource://gre/modules/osfile.jsm');
Cu.import('resource://gre/modules/Services.jsm');
function audioContextCheck() {
if (typeof Services.appShell.hiddenDOMWindow.AudioContext !== 'undefined') {
return new Services.appShell.hiddenDOMWindow.AudioContext();
} else if (typeof Services.appShell.hiddenDOMWindow.mozAudioContext !== 'undefined') {
return new Services.appShell.hiddenDOMWindow.mozAudioContext();
} else {
throw new Error('AudioContext not supported');
}
}
var audioContext = audioContextCheck();
var audioBuffer;
var getSound = new XMLHttpRequest();
getSound.open('get', OS.Path.toFileURI(OS.Path.join(OS.Constants.Path.desktopDir, 'zirzir.mp3')), true);
getSound.responseType = 'arraybuffer';
getSound.onload = function() {
audioContext.decodeAudioData(getSound.response, function(buffer) {
audioBuffer = buffer;
var playSound = audioContext.createBufferSource();
playSound.buffer = audioBuffer;
playSound.connect(audioContext.destination);
playSound.start(audioContext.currentTime);
});
};