首页 > 解决方案 > 如何在 python 3 中将数据从 float64 转换为 int16?

问题描述

目前我正在使用soundfile从 wav 文件中读取音频数据,如下所示:

import soundfile
raw_data, sample_rate = soundfile.read(filename)

虽然我意识到您可以 select dtype=int16,但我想知道如何将 float64 值转换为 int16 值(显然会由于舍入而导致精度损失,这被认为是可以接受的)。

标签: python-3.xcastingfloating-pointintwav

解决方案


soundfile取决于numpy所以我假设你已经安装了,那么你可以做这样的事情:

import numpy as np

# double-check your signal is in the range of -1..1
max_val = np.max(raw_data)
print(str(max_val))

# map to 16-bit
max_16bit = 2**15
raw_data = raw_data * max_16bit

# now change the data type
raw_data = raw_data.astype(np.int16)

推荐阅读