我一直在尝试使用以下代码生成正弦波,并以我的扬声器播放它,但这听起来太可怕了。有人知道为什么吗?它听起来不像正弦波。
dur = int(FS * float(duration) / 1000)
for i in range(dur):
a = frequency * i * 2 * math.pi / FS
y = math.sin(a)
outbuf[i] = y * 0.2
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=44100, output=True)
stream.write(outbuf)
stream.stop_stream()
stream.close()
p.terminate()
play_sound("sine", 1000, 1, 1000)
最佳答案
音频缓冲区必须打包为二进制文件,对于python3,请使用b''.join(struct.pack
还通过将 Angular theta增量常数移到循环外部简化了sin曲线的合成
import pyaudio
import numpy as np
import math
import struct
FS = 44100 # frames per second, samples per second or sample rate
def play_sound(type, frequency, volume, duration):
generate_sound(type, frequency, volume, duration)
def generate_sound(type, frequency, volume, duration):
outbuf = np.random.normal(loc=0, scale=1, size=int(float(duration / 1000.0)*FS))
if type == "sine":
dur = int(FS * float(duration / 1000.0))
theta = 0.0
incr_theta = frequency * 2 * math.pi / FS # frequency increment normalized for sample rate
for i in range(dur):
outbuf[i] = volume * math.sin(theta)
theta += incr_theta
p = pyaudio.PyAudio()
stream = p.open(format=pyaudio.paFloat32, channels=1, rate=FS, output=True)
data = b''.join(struct.pack('f', samp) for samp in outbuf) # must pack the binary data
stream.write(data)
stream.stop_stream()
stream.close()
p.terminate()
play_sound("sine", 220, 0.8, 1000) # duration in milliseconds
关于python - 在python中生成正弦波声音,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/61576953/