在JavaScript中将float值转换为uint8数组 [英] Convert float values to uint8 array in javascript

查看:1466
本文介绍了在JavaScript中将float值转换为uint8数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有音频文件中值的Float32Array.我想将其保存为.wav文件,因此需要将这些值转换为Uint8array.

I have a Float32Array with values from an audio file.I want to save it as a .wav file so I need to convert that values to a Uint8array.

要从uint8转换为float,我首先转换为int16数组,然后转换为Float32Array(

To convert from uint8 to float I convert first to an int16 array and then to a Float32Array (Convert int16 array to float) How can I do that conversion in the other direction?

推荐答案

您可以转换为ArrayBuffer,将数据复制到其中,然后创建此缓冲区的字节视图:

You can convert to an ArrayBuffer, copy the data into and then create a byte view of this buffer :

var data = new Float32Array([0.1, 0.2, 0.3]);

var buffer = new ArrayBuffer(data.byteLength);
var floatView = new Float32Array(buffer).set(data);
var byteView = new Uint8Array(buffer);

此函数可以将任何TypedArray转换为任何其他类型的TypedArray:

This function can convert any TypedArray to any other kind of TypedArray :

function convertTypedArray(src, type) {
    var buffer = new ArrayBuffer(src.byteLength);
    var baseView = new src.constructor(buffer).set(src);
    return new type(buffer);
}

示例:

convertTypedArray(new Float32Array([0.5, 0.3, -0.1]), Uint8Array);

编辑

正如Ian在评论部分中指出的那样,您可以使用TypedArray.buffer访问ArrayBuffer,因此您只需执行以下操作即可:

Edit

As Ian pointed out in the comment section, you can access the ArrayBuffer with TypedArray.buffer, so you can simply do :

var byteArray = new Uint8Array(floatArray.buffer);

请注意,这样做byteArrayfloatArray将共享相同的缓冲区,因此修改byteArray会修改floatArray,反之亦然.

Note that doing this, byteArray and floatArray will share the same buffer, so modifying byteArray will modify floatArray and vice versa.

这篇关于在JavaScript中将float值转换为uint8数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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