Python脚本
开发者套件支持接入USB音频设备,如麦克风或扬声器并调用Python脚本进行录音和播放,Python脚本可集成至其他使用USB音频设备的场景,方便用户进行二次开发。

开发者套件默认仅root用户可访问声卡,普通用户若需使用,请通过root用户将普通用户添加到对应用户组,以HwHiAiUser用户为例。
usermod -a -G audio HwHiAiUser
准备依赖
- Ubuntu22.04镜像:
pip3 install sounddevice soundfile apt-get install libportaudio2
- OpenEuler22.03镜像:
pip3 install sounddevice soundfile yum install portaudio portaudio-devel
录音设备样例代码
- 编写录音样例代码。
import sounddevice as sd from scipy.io import wavfile # 设置录音时长(以秒为单位) duration = 5 # 设置采样率,采样率根据设备而定,常见采样率有44100, 48000,16000等 sample_rate = 16000 # 录音设备ID,即对应 arecord -l 回显中每个设备的card编号 device_index = 0 # 录音通道数,根据设备而定,常见通道数为1,2 channels = 1 # 设置输出音频文件名称 output_file = "output.wav" # 开始录音 print("Recording started...") audio = sd.rec(int(duration * sample_rate), samplerate=sample_rate, channels=channels, blocking=True, device=device_index) print("Recording finished.") # 将录音保存为wav格式的文件 wavfile.write(output_file, sample_rate, audio) print("Audio saved to", output_file)
- 执行脚本录制音频。
python3 record.py
回显如下:
Recording started... Recording finished. Audio saved to output.wav
播放设备样例代码
- 编写播放音频样例代码。
import sounddevice as sd import soundfile as sf # 播放设备ID,即对应 aplay -l 回显中每个设备的card编号 device_index = 0 # 设置录音文件路径 filepath = "output.wav" # 读取录音数据和采样率 data, sample_rate = sf.read(filepath) print("Playing recorded audio...") sd.play(data, samplerate=sample_rate, blocking=True, device=device_index) print("Playback finished.")
- 执行脚本播放音频。
python3 play.py
回显如下:
Playing recorded audio... Playback finished.
父主题: 对接USB音频设备