gpt4 book ai didi

javascript - 将表示为 numpy 数组的音频数据从 python 发送到 Javascript

转载 作者:行者123 更新时间:2023-12-05 03:56:24 25 4
gpt4 key购买 nike

我有一个 TTS(文本到语音)系统,它以 numpy 数组形式生成音频,其数据类型为 np.float32。这个系统在后台运行,我想把后台的数据传输到前台,以便在某个事件发生时播放。

这个问题显而易见的解决方案是将音频数据写入磁盘为wav文件,然后将路径传递给前端进行播放。这工作正常,但出于管理原因我不想这样做。我只想将音频数据(numpy 数组)传输到前端。

到目前为止我所做的是:

后端

text = "Hello"
wav, sr = tts_model.synthesize(text)
data = {"snd", wav.tolist()}
flask_response = app.response_class(response=flask.json.dumps(data),
status=200,
mimetype='application/json' )
# then return flask_response

前端

// gets wav from backend
let arrayData = new Float32Array(wav);
let blob = new Blob([ arrayData ]);
let url = URL.createObjectURL(blob);
let snd = new Audio(url);
snd.play()

我到目前为止所做的,但是 JavaScript 抛出以下错误:

Uncaught (in promise) DOMException: Failed to load because no supported source was found.

这就是我要做的事情的要点。很抱歉,您没有 TTS 系统,因此无法重现错误,所以这是一个 audio file由它生成,您可以使用它来查看我做错了什么。

我尝试过的其他事情:

  • 将音频数据类型更改为 np.int8np.int16 以通过 Int8Array() 在 JavaScript 中转换分别为 int16Array()
  • 在创建 blob 时尝试了不同的类型,例如 {"type": "application/text;charset=utf-8;"}{"type": "audio/ogg; codecs=opus;".

我已经在这个问题上苦苦挣扎了很长时间,所以欢迎任何帮助!!

最佳答案

将 wav 值数组转换为字节

在合成之后,您可以立即将 wav 的 numpy 数组转换为字节对象,然后通过 base64 进行编码。

import io
from scipy.io.wavfile import write

bytes_wav = bytes()
byte_io = io.BytesIO(bytes_wav)
write(byte_io, sr, wav)
wav_bytes = byte_io.read()

audio_data = base64.b64encode(wav_bytes).decode('UTF-8')

这可以直接用于创建 html 音频标签作为源(使用 flask):

<audio controls src="data:audio/wav;base64, {{ audio_data }}"></audio>

因此,您只需将wavsr 转换为代表原始.wav 文件的audio_data。并用作 Flask 应用程序的 render_template 参数。 (不发送的解决方案)

或者,如果您发送 audio_data,在您接受响应的 .js 文件中,使用 audio_data 构建 url(将放置为 src 属性,就像在 html 中一样):

// get audio_data from response

let snd = new Audio("data:audio/wav;base64, " + audio_data);
snd.play()

因为:

Audio(url) Return value:A new HTMLAudioElement object, configured to be used for playing back the audio from the file specified by url.The new object's preload property is set to auto and its src property is set to the specified URL or null if no URL is given. If a URL is specified, the browser begins to asynchronously load the media resource before returning the new object.

关于javascript - 将表示为 numpy 数组的音频数据从 python 发送到 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59338606/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com