![](/img/trans.png)
[英]Is there anyway I can record the sound that comes from my computer and save it to a wav or mp3 file in python?
[英]How do I store the sound generated in this pyaudio stream into a WAV or MP3 file?
"""Play a fixed frequency sound."""
from __future__ import division
import math
from pyaudio import PyAudio
def sine_tone(frequency, duration, volume=1, sample_rate=22050):
n_samples = int(sample_rate * duration)
restframes = n_samples % sample_rate
p = PyAudio()
stream = p.open(format=p.get_format_from_width(1), # 8bit
channels=1, # mono
rate=sample_rate,
output=True)
s = lambda t: volume * math.sin(2 * math.pi * frequency * t / sample_rate)
samples = (int(s(t) * 0x7f + 0x80) for t in range(n_samples))
for buf in zip(*[samples]*sample_rate): # write several samples at a time
stream.write(bytes(bytearray(buf)))
# fill remainder of frameset with silence
stream.write(b'\x80' * restframes)
stream.stop_stream()
stream.close()
p.terminate()
def playScale(scale):
for x in scale:
print(x)
sine_tone(frequency = x,
duration = 1,
volume=.5,
sample_rate = 50000)
playScale函数接受一个频率数组,并使用sine_tone函数播放它们。 如何将这一系列声音保存到.WAV文件或.MP3文件中?
您应该将所有音频数据写入一个流,然后可以使用python中的“ wave”库保存此流,该库可用于处理wave文件。
但是,由于您正在为每种声音/音调编写单独的流,因此不确定当前的代码如何工作。 可能希望将流传递给该函数,以便您也可以附加该流,并在以后呈现所有音频时使用其他函数进行保存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.