目录
pip install pyaudio wave
import pyaudio
import wave
CHUNK = 1024
audio_file = 'output.wav'
wf = wave.open(audio_file, 'rb')
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
channels=wf.getnchannels(),
rate=wf.getframerate(),
output=True)
data = wf.readframes(CHUNK)
while data != b"":
stream.write(data)
data = wf.readframes(CHUNK)
stream.stop_stream()
stream.close()
p.terminate()
import pyaudio
import wave
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 5
WAVE_OUTPUT_FILENAME = "output.wav"
p = pyaudio.PyAudio()
stream = p.open(format=FORMAT,
channels=CHANNELS,
rate=RATE,
input=True,
frames_per_buffer=CHUNK)
print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
import sys
import pyaudio
RECORD_SECONDS = 5
CHUNK = 1024
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1 if sys.platform == 'darwin' else 2,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
print('* recording')
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
stream.write(stream.read(CHUNK))
print('* done')
stream.close()
p.terminate()
import time
import sys
import pyaudio
DURATION = 5 # seconds
def callback(in_data, frame_count, time_info, status):
return (in_data, pyaudio.paContinue)
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(2),
channels=1 if sys.platform == 'darwin' else 2,
rate=44100,
input=True,
output=True,
stream_callback=callback)
start = time.time()
while stream.is_active() and (time.time() - start) < DURATION:
time.sleep(0.1)
stream.close()
p.terminate()
如果你的电脑是Mac M1的话,安装pyaudio可能会遇到问题。可以看下面的博客去解决。
免费下载wav 音频的网站
参考资料
PyAudio: Cross-platform audio I/O for Python, with PortAudio