当前位置: 首页 > 工具软件 > PyAudio > 使用案例 >

pyaudio录制音频和播放音频

孟思远
2023-12-01

目录

前期准备

播放音频文件

录制音频文件

曾遇到的问题

其它


前期准备

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()

检测声音并播放-用callback方式

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可能会遇到问题。可以看下面的博客去解决。

[Mac M1] 错误xcrun: error: (/Library/Developer/CommandLineTools) || #include “portaudio.h“_茫茫人海一粒沙的博客-CSDN博客

其它

免费下载wav 音频的网站

人类 音效 wav 免费下载 - 爱给网

参考资料

PyAudio: Cross-platform audio I/O for Python, with PortAudio

基于 Python 的声音检测:PyAudio - 简书

 类似资料: