如何在浏览器中使用 JavaScript 播放音频字节数组(不是文件!) [英] How to play audio byte array (not file!) with JavaScript in a browser

查看:63
本文介绍了如何在浏览器中使用 JavaScript 播放音频字节数组(不是文件!)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

出于安全原因,我不允许将 WAV 文件存储在服务器上以供浏览器访问.我拥有的是一个字节数组,其中包含服务器上的音频数据(我相信是 WAV 文件的数据部分),我希望它通过 JavaScript(或 Applet 但首选 JS)在浏览器上播放,我可以使用 JSON-PRC 将整个 byte[] 发送过去,或者我可以打开一个套接字来流式传输它,但在任何一种情况下我都不知道谁在浏览器中播放 byte[]?

For mostly security reasons, I'm not allowed to store a WAV file on the server to be accessed by a browser. What I have is a byte array contains audio data (the data portion of a WAV file I believe) on the sever, and I want it to be played on a browser through JavaScript (or Applet but JS preferred), I can use JSON-PRC to send the whole byte[] over, or I can open a socket to stream it over, but in either case I don't know who to play the byte[] within the browser?

推荐答案

以下代码将在 0.5 和 2.0 处播放正弦波.在您的按钮或任何您想要的地方调用函数 play_buffersource().

The following code will play the sine wave at 0.5 and 2.0. Call the function play_buffersource() in your button or anywhere you want.

使用启用了网络音频标志的 Chrome 进行测试.对于您的情况,您需要做的只是将音频字节洗牌到 buf.

Tested using Chrome with Web Audio flag enabled. For your case, all that you need to do is just to shuffle your audio bytes to the 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>

参考文献:

如果您需要重新采样音频,可以使用 JavaScript 重新采样器:https://github.com/grantgalitz/XAudioJS

If you need to resample the audio, you can use a JavaScript resampler: https://github.com/grantgalitz/XAudioJS

如果需要对base64数据进行解码,有很多JavaScript base64解码器:https://github.com/carlo/jquery-base64

If you need to decode the base64 data, there are a lot of JavaScript base64 decoder: https://github.com/carlo/jquery-base64

这篇关于如何在浏览器中使用 JavaScript 播放音频字节数组(不是文件!)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆