在Python中创建aiff文件并使用soundfile和sounddevice播放

2024-05-20 23:58:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我成功地将soundfile用于aiff文件,但我希望生成具有明确傅立叶分量的声音

我在网上收集了一些代码,并将它们放在一起创建了一个aiff文件,然后尝试将其读回。我得到的代码如下所示。我知道我很接近,但我似乎在aiff文件的二进制编码中迷失了方向。我尝试了很多方法,使用h(短整数,振幅变化为32767)作为正弦函数,并使用int())和f(float),它给出了一些类似于我正在寻找的声音,但失真很大。感谢您的帮助!(我在macosx catalina和python 3.8上工作,编码是little endian,所以我在struct语句中使用了<;)

import aifc,struct
import numpy as np
import soundfile as sf
import sounddevice as sd

sampleRate = 44100 # hertz
seconds = 3 # seconds
frequency = 440.0 # hertz

obj = aifc.open('sound.aif','w')
obj.setnchannels(1) # mono
obj.setsampwidth(2)
obj.setframerate(sampleRate)

t = np.linspace(0, seconds, seconds * sampleRate, False)
value=[]
for i in t:
    value.append(np.sin(i*frequency*2*np.pi))

# This is the line that troubles me...
data = struct.pack('<'+'f'*len(value), *value)

plt.figure()
plt.plot(t[0:100],value[0:100])
plt.show()

obj.writeframes( data )
obj.close()

obj = aifc.open('sound.aif','r')
print( "Number of channels",obj.getnchannels())
print ( "Sample width",obj.getsampwidth())
print ( "Frame rate.",obj.getframerate())
print ("Number of frames",obj.getnframes())
print ( "parameters:",obj.getparams())
obj.close()

data, fs = sf.read('sound.aif')
sd.play(data, fs, blocking=True)

Tags: 文件importobjdatavalueasnpstruct