问题
I want to add ability to my addon to play audio from URL. At MDN I not found information about this. I found this and this and this and this answers - but this is about local file and what the correct answer for 2015 year?
回答1:
I have an answer from 2016 ;)
That code will not work with Multi-process Firefox (will be released in 2016):
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = new window.Audio('http://example.com/audio.mp3');
vaudio.play();
Because sdk/window/utils
. To understand why read this topic on MDN.
Solution is 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();
});
It works in my extension and will work with new Multi-process Firefox release.
回答2:
@Noitidart Future is coming and at 2015 you can write much less code!
var window = require('sdk/window/utils').getMostRecentBrowserWindow();
var audio = new window.Audio('http://example.com/audio.mp3');
audio.play();
回答3:
This works for me Im not sure how 2015 it is, but i wrote like a couple months ago:
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);
});
};
来源:https://stackoverflow.com/questions/32755863/firefox-sdk-correct-way-to-play-audio-from-the-url-in-2015-year