Alm*_*lmo 6 firefox greasemonkey content-security-policy
var audioPlayer = new Audio("http://URLTOMYSOUND/ping.mp3");
audioPlayer.play();
Run Code Online (Sandbox Code Playgroud)
加载音频时出现此错误:
内容安全策略:页面的设置阻止了加载资源...
我该如何解决这个问题?我不在乎声音在哪里,我只想玩它.它可能是本地的,但我的印象是本地文件访问也是禁忌.
如果您遇到Greasemonkey 2.3中的内容安全策略(CSP)问题,则无法(此时)从文件播放声音.如果您可以修改要运行的站点的HTTP标头,则可以.请参阅使用内容安全策略和CSP策略指令.
使用GM_xmlhttpRequest"允许这些请求跨越相同的原始策略边界",由于当前GM 2.3中的错误而无效.请参阅问题#2045.问题源于无法将ArrayBuffer复制到沙箱中以获得正确的解码权限等.
下面的代码段应该适用于未来的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's 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);
}
Run Code Online (Sandbox Code Playgroud)
现在,如果你只需要一些声音,我会用振荡器在程序上生成它.以下演示使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1053 次 |
| 最近记录: |