3 回答

TA贡献1852条经验 获得超7个赞
这听起来像是一个量化问题。如果波形文件中的样本存储为 asfloat并且 librosa 只是对 an 执行直接转换int,则小于 1 的值将被截断为 0。很有可能,这就是为什么sig是全零数组的原因。在float必须被缩放以将其映射到的范围int。例如,
>>> a = sp.randn(10)
>>> a
array([-0.04250369, 0.244113 , 0.64479281, -0.3665814 , -0.2836227 ,
-0.27808428, -0.07668698, -1.3104602 , 0.95253315, -0.56778205])
将 a 转换为类型int而不缩放
>>> a.astype(int)
array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
将 a 转换int为 16 位整数的缩放比例
>>> b = (a* 32767).astype(int)
>>> b
array([ -1392, 7998, 21127, -12011, -9293, -9111, -2512, -42939,
31211, -18604])
转换缩放int回float
>>> c = b/32767.0
>>> c
array([-0.04248177, 0.24408704, 0.64476455, -0.36655782, -0.28360851,
-0.27805414, -0.0766625 , -1.31043428, 0.9525132 , -0.56776635])
cb由于量化为,并且仅等于大约 3 或 4 个小数位int。
如果 librosa 返回 a float,您可以按比例缩放2**15并将其转换为 anint以获得与 scipy wave reader 返回的相同范围的值。由于 librosa 正在返回 a float,因此值可能会位于一个小得多的范围内,例如[-1, +1],而不是将在[-32768, +32767]. 所以你需要缩放一个以获得匹配的范围。例如,
sig, rate = librosa.load(spec_file, mono=True)
sig = sig × 32767

TA贡献1836条经验 获得超4个赞
补充一下,Librosa 有一个实用程序可以将整数数组转换为浮点数。
float_audio = librosa.util.buf_to_float(sig)
在生成 Pydub 音频段的频谱图时,我使用它取得了巨大的成功。请记住,它的参数之一是每个样本的字节数。它默认为 2。您可以在此处的文档中了解更多信息。这是源代码:
def buf_to_float(x, n_bytes=2, dtype=np.float32):
"""Convert an integer buffer to floating point values.
This is primarily useful when loading integer-valued wav data
into numpy arrays.
See Also
--------
buf_to_float
Parameters
----------
x : np.ndarray [dtype=int]
The integer-valued data buffer
n_bytes : int [1, 2, 4]
The number of bytes per sample in `x`
dtype : numeric type
The target output type (default: 32-bit float)
Returns
-------
x_float : np.ndarray [dtype=float]
The input data buffer cast to floating point
"""
# Invert the scale of the data
scale = 1./float(1 << ((8 * n_bytes) - 1))
# Construct the format string
fmt = '<i{:d}'.format(n_bytes)
# Rescale and format the data buffer
return scale * np.frombuffer(x, fmt).astype(dtype)
添加回答
举报