It is currently not possible to play sound from a file if you are using Content Security Policy (CSP) issues, as in Greasemonkey 2.3. If you can change the HTTP headers of the site you want to work on, this is possible. See Using the content security policy and the CSP policy directive .
Using GM_xmlhttpRequest , which "allows these requests to cross the same boundaries of the origin policy", does not work due to an error in the current GM 2.3. See issue # 2045 . The problem is due to the inability to copy ArrayBuffer to the sandbox ground to get proper permissions for decoding, etc.
The snippet below should work in future versions of GM.
// ==UserScript== // @name Testing Web Audio: Load from file // @namespace http://ericeastwood.com/ // @include http://example.com/ // @version 1 // @grant GM_xmlhttpRequest // ==/UserScript== window.AudioContext = window.AudioContext || window.webkitAudioContext; var context = new AudioContext(); // Note: this is not an actual reference to a real mp3 var url = 'http://example.com/some.mp3'; var soundLoadedPromise = new Promise(function(resolve, reject) { // This will get around the CORS issue // http://wiki.greasespot.net/GM_xmlhttpRequest var req = GM_xmlhttpRequest({ method: "GET", url: url, responseType: 'arraybuffer', onload: function(response) { try { context.decodeAudioData(response.response, function(buffer) { resolve(buffer) }, function(e) { reject(e); }); } catch(e) { reject(e); } } }); }); soundLoadedPromise.then(function(buffer) { playSound(buffer); }, function(e) { console.log(e); }); function playSound(buffer) { // creates a sound source var source = context.createBufferSource(); // tell the source which sound to play source.buffer = buffer; // connect the source to the context destination (the speakers) source.connect(context.destination); // play the source now // note: on older systems, may have to use deprecated noteOn(time); source.start(0); }
For now, if you only need sound, I just process it with an oscillator. The demo below uses AudioContext.createOscillator .
// ==UserScript== // @name Test Web Audio: Oscillator - Web Audio // @namespace http://ericeastwood.com/ // @include http://example.com/ // @version 1 // @grant none // ==/UserScript== window.AudioContext = window.AudioContext || window.webkitAudioContext; context = new AudioContext(); var o = context.createOscillator(); o.type = 'sine'; o.frequency.value = 261.63; o.connect(context.destination); // Start the sound o.start(0); // Play the sound for a second before stopping it setTimeout(function() { o.stop(0); }, 1000);
source share