Firefox SDK:播放 2015 年 url 音频的正确方法?

Firefox SDK: correct way to play audio from the url in 2015 year?

我想为我的插件添加播放来自 URL 的音频的功能。在 MDN I not found information about this. I found this and this and this and this 个答案中 - 但这是关于本地文件的,2015 年的正确答案是什么?

这对我有用我不确定 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);
    });
};

@Noitidart 未来已来,2015年你可以写更少的代码!

var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = new window.Audio('http://example.com/audio.mp3');
audio.play();

我有一个 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 版本一起工作。