python-3.x - 如何在 python 3 中将数据从 float64 转换为 int16?
问题描述
目前我正在使用soundfile
从 wav 文件中读取音频数据,如下所示:
import soundfile
raw_data, sample_rate = soundfile.read(filename)
虽然我意识到您可以 select dtype=int16
,但我想知道如何将 float64 值转换为 int16 值(显然会由于舍入而导致精度损失,这被认为是可以接受的)。
解决方案
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)
推荐阅读
- string - 如何子串 0 到 30,但前提是有超过 30 个字符
- python - 安装 django-cors-middleware 的问题
- postgresql - 关系“schema.table”不存在使用 slick 3.3.3 时抛出的异常
- linux - 不允许程序杀死任何未关联的进程
- html - 如何在一个 css 文件中使用不同的颜色主题
- symfony - Symfony 5 表单集合的问题
- python - 我应该在 keras 中使用什么损失函数和度量来进行多标签分类?
- java - 无法在 Android Studio 中读取 JSON
- c++ - ESP32 尝试重新连接到网络断开时没有停止循环(Arduino)
- python - 使用 AES-GCM 加密不适合 RAM 的大文件