在播放器上的浏览器上播放 wav 字节数据

Meh*_*egi 3 html javascript audio

有人可以帮助我解决这个问题吗?我有点困惑,我正在从数据库获取 wav 数据,并且我可以使用此功能在浏览器上播放此 wav 数据:

function playWave(byteArray) {
    var audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    var myAudioBuffer = audioCtx.createBuffer(1, byteArray.length, 8000);
    var nowBuffering = myAudioBuffer.getChannelData(0);
    for (var i = 0; i < byteArray.length; i++) {
        nowBuffering[i] = byteArray[i];
    }

    var source = audioCtx.createBufferSource();
    source.buffer = myAudioBuffer;
    source.connect(audioCtx.destination);
    source.start();
}
Run Code Online (Sandbox Code Playgroud)

一切工作正常,我只需要一个 GUI 播放器来播放/暂停/停止并最终绘制频谱。

首先我尝试使用 HTML5 的音频标签,但你需要在 src 参数中放置一个有效的 url :

<audio controls="controls">
  Your browser does not support the &lt;audio&gt; tag. 
  <source src="../m/example.mp3" />
</audio> 
Run Code Online (Sandbox Code Playgroud)

是否可以将 src 参数更改为类似可以放置和播放字节数组的方法?有没有玩家可以应对这种情况呢?我只想在播放器上以一定的速率(8000Hz)播放数据库中的wav(播放/暂停/停止),这似乎是一个简单的问题,但我在互联网上没有发现任何文章或文档讨论这一点。我在互联网上找到的唯一播放器,您需要提供有效的文件。

Fab*_*ltz 6

Blob正确转换后应该可以使用byteArray。然后,您可以创建一个 blob 对象 URL 并将其设置srcsource内容:

\n\n

\r\n
\r\n
// Create blob from Uint8Array & Object URL.\r\nconst blob = new Blob([getByteArray()], { type: \'audio/wav\' });\r\nconst url = URL.createObjectURL(blob);\r\n\r\n// Get DOM elements.\r\nconst audio = document.getElementById(\'audio\');\r\nconst source = document.getElementById(\'source\');\r\n\r\n// Insert blob object URL into audio element & play.\r\nsource.src = url;\r\naudio.load();\r\naudio.play();\r\n\r\n// Get data from database/server, hardcoded here for simplicity.\r\nfunction getByteArray() {\r\n  const data = [82, 73, 70, 70, 222, 37, 0, 0, 87, 65, 86, 69, 102, 109, 116, 32, 16, 0, 0, 0, 1, 0, 1, 0, 68, 172, 0, 0, 136, 88, 1, 0, 2, 0, 16, 0, 100, 97, 116, 97, 186, 37, 0, 0, 0, 0, 255, 12, 2, 27, 254, 40, 2, 55, 254, 68, 1, 83, 0, 83, 0, 69, 0, 55, 255, 40, 2, 27, 253, 12, 3, 255, 254, 240, 0, 227, 1, 213, 255, 198, 1, 185, 255, 170, 1, 175, 255, 188, 1, 203, 255, 216, 1, 231, 255, 244, 2, 3, 254, 16];\r\n\r\n  // Convert byteArray into Uint8Array.\r\n  return new Uint8Array(data);\r\n}
Run Code Online (Sandbox Code Playgroud)\r\n
<audio controls="controls" id="audio" loop>\r\n  Your browser does not support the &lt;audio&gt; tag. \r\n  <source id="source" src="" type="audio/wav" />\r\n</audio>
Run Code Online (Sandbox Code Playgroud)\r\n
\r\n
\r\n

\n\n

\xe2\x98\x9d\xef\xb8\x8f 单击时会播放声音!

\n