101 lines
2.6 KiB
Python
101 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
||
"""
|
||
简单的音频测试脚本,用于诊断树莓派上的音频问题
|
||
"""
|
||
|
||
import pyaudio
|
||
import time
|
||
import os
|
||
|
||
def test_audio():
|
||
"""测试音频设备"""
|
||
print("=== 音频设备测试 ===")
|
||
|
||
pa = pyaudio.PyAudio()
|
||
|
||
# 列出所有设备
|
||
print("\n可用的音频设备:")
|
||
for i in range(pa.get_device_count()):
|
||
info = pa.get_device_info_by_index(i)
|
||
print(f" 设备 {i}: {info['name']}")
|
||
print(f" 输入通道: {info['maxInputChannels']}")
|
||
print(f" 输出通道: {info['maxOutputChannels']}")
|
||
print(f" 默认采样率: {info['defaultSampleRate']}")
|
||
print()
|
||
|
||
# 查找默认输入设备
|
||
default_input = pa.get_default_input_device_info()
|
||
print(f"默认输入设备: {default_input['name']} (索引: {default_input['index']})")
|
||
|
||
# 查找默认输出设备
|
||
default_output = pa.get_default_output_device_info()
|
||
print(f"默认输出设备: {default_output['name']} (索引: {default_output['index']})")
|
||
|
||
pa.terminate()
|
||
|
||
def test_recording():
|
||
"""测试录音功能"""
|
||
print("\n=== 录音测试 ===")
|
||
|
||
pa = pyaudio.PyAudio()
|
||
|
||
try:
|
||
# 设置录音参数
|
||
FORMAT = pyaudio.paInt16
|
||
CHANNELS = 1
|
||
RATE = 16000 # 降低采样率,使用设备默认的44100
|
||
CHUNK = 1024
|
||
|
||
print(f"尝试打开音频流,采样率: {RATE}")
|
||
|
||
# 打开音频流
|
||
stream = pa.open(
|
||
format=FORMAT,
|
||
channels=CHANNELS,
|
||
rate=RATE,
|
||
input=True,
|
||
frames_per_buffer=CHUNK
|
||
)
|
||
|
||
print("开始录音5秒...")
|
||
frames = []
|
||
|
||
# 录音5秒
|
||
for i in range(0, int(RATE / CHUNK * 5)):
|
||
data = stream.read(CHUNK)
|
||
frames.append(data)
|
||
if i % 10 == 0:
|
||
print(f"录音中... {i * CHUNK / RATE:.1f}秒")
|
||
|
||
print("录音完成")
|
||
|
||
# 停止流
|
||
stream.stop_stream()
|
||
stream.close()
|
||
|
||
# 播放录音
|
||
print("播放录音...")
|
||
stream = pa.open(
|
||
format=FORMAT,
|
||
channels=CHANNELS,
|
||
rate=RATE,
|
||
output=True
|
||
)
|
||
|
||
for frame in frames:
|
||
stream.write(frame)
|
||
|
||
stream.stop_stream()
|
||
stream.close()
|
||
|
||
print("播放完成")
|
||
|
||
except Exception as e:
|
||
print(f"录音测试失败: {e}")
|
||
|
||
finally:
|
||
pa.terminate()
|
||
|
||
if __name__ == "__main__":
|
||
test_audio()
|
||
test_recording() |