【问题标题】:How do you convert data from float64 to int16 in python 3?如何在 python 3 中将数据从 float64 转换为 int16?
【发布时间】:2018-10-08 10:27:29
【问题描述】:

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

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

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

【问题讨论】:

  • @Reza Mousavi Rejected your edit as whilst' and realise' 都可以在英式英语中以这种方式使用。两者都用美式英语死了,但唉......我是英国人
  • 对不起,这是我的错
  • 没关系,英式英语很奇怪:)

标签: python-3.x casting floating-point int wav


【解决方案1】:

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)

【讨论】:

    猜你喜欢
    • 2015-04-01
    • 1970-01-01
    • 2015-12-12
    • 2012-02-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多