出于安全原因,我不允许在服务器上存储WAV文件以供浏览器访问.我所拥有的是一个字节数组包含服务器上的音频数据(我相信WAV文件的数据部分),我希望它通过JavaScript(或Applet,但首选JS)在浏览器上播放,我可以使用JSON- PRC发送整个byte [],或者我可以打开一个套接字来流过它,但在任何一种情况下我都不知道在浏览器中播放byte []的人是谁?
以下代码将播放0.5和2.0的正弦波.play_buffersource()在您的按钮或任何您想要的地方调用该功能.
使用启用了Web音频标记的Chrome进行测试.对于您的情况,您需要做的只是将您的音频字节随机播放到buf.
<script type="text/javascript">
const kSampleRate = 44100; // Other sample rates might not work depending on the your browser's AudioContext
const kNumSamples = 16834;
const kFrequency = 440;
const kPI_2 = Math.PI * 2;
function play_buffersource() {
if (!window.AudioContext) {
if (!window.webkitAudioContext) {
alert("Your browser sucks because it does NOT support any AudioContext!");
return;
}
window.AudioContext = window.webkitAudioContext;
}
var ctx = new AudioContext();
var buffer = ctx.createBuffer(1, kNumSamples, kSampleRate);
var buf = buffer.getChannelData(0);
for (i = 0; i < kNumSamples; ++i) {
buf[i] = Math.sin(kFrequency * kPI_2 * i / kSampleRate);
}
var node = ctx.createBufferSource(0);
node.buffer = buffer;
node.connect(ctx.destination);
node.noteOn(ctx.currentTime + 0.5);
node = ctx.createBufferSource(0);
node.buffer = buffer;
node.connect(ctx.destination);
node.noteOn(ctx.currentTime + 2.0);
}
</script>
Run Code Online (Sandbox Code Playgroud)
参考文献:
如果您需要重新采样音频,可以使用JavaScript重采样器:https://github.com/grantgalitz/XAudioJS
如果你需要解码base64数据,那么有很多JavaScript base64解码器:https://github.com/carlo/jquery-base64
我怀疑你可以使用 HTML5 Audio API 轻松实现这一点:
https://developer.mozilla.org/en/Introducing_the_Audio_API_Extension
这个库也可能会派上用场,尽管我不确定它是否反映了最新的浏览器行为:
https://github.com/jussi-kalliokoski/audiolib.js
| 归档时间: |
|
| 查看次数: |
11931 次 |
| 最近记录: |