使用 SciPy 中的 wavfile.write 在 Python 中编写 wav 文件 [英] Writing wav file in Python with wavfile.write from SciPy
问题描述
我有这个代码:
import numpy as np
import scipy.io.wavfile
import math
rate, data = scipy.io.wavfile.read('xenencounter_23.wav')
data2 = []
for i in range(len(data)):
data2.append([int(round(math.sin(data[i][0])*3000)), int(round(math.sin(data[i][1])*3000))])
data2 = np.asarray(data2)
print data2
scipy.io.wavfile.write('xenencounter_23sin3.wav',rate,data2)
这会打印(截断):
[[-2524 2728]
[ -423 -2270]
[ 2270 423]
...,
[-2524 0]
[ 2524 -2728]
[-2270 838]]
wav 文件在 Windows Media Player 中打开并播放,因此至少它的格式正确.然而,当用 Audacity 打开它并查看单个样本时,它们都是 0,并且相应地文件根本没有播放任何声音.
The wav file opens and plays in Windows Media Player, so at least its the proper format. However, when opening it with Audacity and looking at the individual samples, they're all 0, and concordantly the file plays no sound at all.
我不明白的是上面列出的 numpy 数组是如何变成全 0 的.它应该低于样本的最大值(或高于,如果它是负数).
What I don't understand is how that numpy array listed above becomes all 0's. It should be below the maximum value for a sample (or above, if it's negative).
推荐答案
我发现 scipy.io.wavfile.write() 以 16 位整数写入,这解释了在尝试使用 32 位整数(默认值)代替.虽然我在 wavfile.write 中找不到改变它的方法,但我确实通过改变找到了:
I found that scipy.io.wavfile.write() writes in 16-bit integer, which explains the larger file sizes when trying to use a 32-bit integer (the default) instead. While I couldn't find a way to change this in wavfile.write, I did find that by changing:
data2 = np.asarray(data2)
到
data2 = np.asarray(data2, dtype=np.int16)
我可以写一个工作文件.
I could write a working file.
这篇关于使用 SciPy 中的 wavfile.write 在 Python 中编写 wav 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!