Firefox addon Firefox SDK:2015年从url播放音频的正确方式?

Firefox addon Firefox SDK:2015年从url播放音频的正确方式?,firefox-addon,firefox-addon-sdk,Firefox Addon,Firefox Addon Sdk,我想给我的插件添加播放URL音频的功能。目前我还没有找到这方面的信息。我找到了答案——但这是关于本地文件的,2015年的正确答案是什么?这对我来说很有效,我不确定2015年会是怎样的,但我几个月前写过: Cu.import('resource://gre/modules/osfile.jsm'); Cu.import('resource://gre/modules/Services.jsm'); function audioContextCheck() { if (typeof Ser

我想给我的插件添加播放URL音频的功能。目前我还没有找到这方面的信息。我找到了答案——但这是关于本地文件的,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年发布):

因为
sdk/window/utils
。要理解为什么要读这篇文章

解决方案是
页面工作者

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

我得到的
XMLHttpRequest未定义
非常非常好!!:)它也适用于本地文件吗?(
文件://
)?我不明白这一行
var audio=('http://example.com/audio.mp3');那只是一个字符串对不起,是的,第二行不正确-现在可以了。我不知道本地文件-你可以在这里检查并写评论,结果如下:)我没有sdk环境,将uri更改为文件uri作为测试是否太难?我为人们做了这么多,难道人们不能为我做一点吗P@Noitidart我尝试了调试
新窗口file:///home/vitaly/Desktop/audio.mp3).play()
我听到了音乐-这是工作:)谢谢!:)这真是个好消息!谢谢,我试试看。
var audio = new window.Audio;

self.port.on('play', function(url) {
    audio.src = url;
    audio.play();
});