我想在.wav文件中写入信号,但是当我使用 scipy.io.wavfile.write它只是创建一个没有声音的.wav文件。 .wav的长度很好,但是没有声音。 我正在寻找针对此问题的解决方案,但找不到帮助。 我的下面的代码:
import scipy as sp
import numpy as np
dt = np.dtype(np.int32)
sig = np.fromfile(filename, dtype=dt, count=-1, sep='')
sp.io.wavfile.write('sound.wav', int(fS), sig)
作为测试,我还做了一些功能:
def write_wav_sin(name,fs,f):
x = np.linspace(0,10,10*fs)
dt = np.dtype(np.float32)
sig = np.sin(2*math.pi*f*x, dtype=dt)
print(type(sig[0]))
sp.io.wavfile.write(name, fs, sig)
plt.plot(x,sig)
通过此测试,它可以工作,但是对于我的其他代码,则不起作用
有人知道为什么我有这个问题吗?
答案 0 :(得分:2)
通过打印sig
和sig.min()
,检查sig.max()
中值的范围。值不会按wavfile.write
进行缩放,因此可能是因为您的文件值太低而无法听到它们。
尝试按比例放大32位整数值,或将数据写为标准化的32位浮点。例如,在保存之前,这会将sig
转换为[-1,1]范围内的32位浮点值:
m = np.max(np.abs(sig))
sigf32 = (sig/m).astype(np.float32)
sp.io.wavfile.write('sound.wav', int(fS), sigf32)
答案 1 :(得分:1)
最后,我将所有信号的幅度最大值除以最小(我的信号有时幅度为500000,以Wav格式将其除以250000)。
有了这个技巧,我可以听声音了,但是有些奇怪的东西,例如附加的伪像/噪声(我将其与使用matlab获得的.wav(具有相同文件)进行了比较)
我使用的代码是:
import scipy as sp
import numpy as np
dt = np.dtype(np.int32)
sig = np.fromfile(filename, dtype=dt, count=-1, sep='')
sp.io.wavfile.write('sound.wav', int(fS), sig/250000)
答案 2 :(得分:0)
这是一个注释示例,说明如何生成具有设置的持续时间,频率,体积和样本数量的基本波形文件。利用NumPy
和Python的wave
库。
import numpy as ny
import struct
import wave
class SoundFile:
def __init__(self, signal):
# https://docs.python.org/3.6/library/wave.html#wave.open
self.file = wave.open('test.wav', 'wb')
self.signal = signal
self.sr = 44100
def write(self):
# https://docs.python.org/3.6/library/wave.html#wave.Wave_write.setparams
self.file.setparams( ( 1, 2, self.sr, 44100 * 4, 'NONE', 'noncompressed' ) )
# https://docs.python.org/3.6/library/wave.html#wave.Wave_write.writeframes
self.file.writeframes( self.signal )
self.file.close()
# signal settings
duration = 4 # duration in Seconds
samplerate = 44100 # Hz (frequency)
samples = duration * samplerate # aka samples per second
frequency = 440 # Hz
period = samplerate / float( frequency ) # of samples
omega = ny.pi * 2 / period # calculate omega (angular frequency)
volume = 16384 # 16384 is the volume measure (max is 32768)
# create sin wave
xaxis = ny.arange( samples, dtype = ny.float )
ydata = volume * ny.sin( xaxis * omega )
# fill blanks
signal = ny.resize( ydata, ( samples, ) )
#create sound file
f = SoundFile( signal )
f.write()
print( 'sound file created' )
由随机博主尽力评论,更新和修改this来源。