跳转到主内容
思享编程网:思考分享,玩转编程世界!

python 录制系统播放的声音

python 录制系统声音 最近做项目遇到一个需求,需要录制系统的声音并且需要实时获取录制到的数据。

从网上搜索得到的结果很多都是通过pyaudio录制立体声混音设备来得到系统的声音,但是这个方法在我的电脑不适用。

经过多次尝试,发现soundcard库可以录制系统的声音,下面介绍具体的实现 确定录制设备 首先需要确定录制什么设备,通过

sc.all_microphones(include_loopback=True)

可以获取到所有的可录制设备,其中可以录制到系统输出声音的设备的 isloopback 属性为 True。

mics = sc.all_microphones(include_loopback=True)

loopback_devices = [] loopback_devices_name = [] for i in range(len(mics)): if mics[i].isloopback is True: loopback_devices.append(mics[i]) loopback_devices_name.append(mics[i].name)

选择合适的设备进行录制

device = loopback_devices[idx]

recorded_data = [] duration = 6 with device.recorder(samplerate, 1) as mic: try: start_time = time.time() while time.time() - start_time < duration: frames = mic.record(numframes=1024) # 录制的结果为浮点数,转为字节,便于写入文件 recorded_data.append((frames * 32768).astype(np.int16).tobytes()) except KeyboardInterrupt: print("\nRecording stopped.")

写入文件 使用wave库写入音频

with wave.open(filename, mode="wb") as wav_file:

wav_file.setnchannels(1) wav_file.setsampwidth(2) wav_file.setframerate(samplerate) for i in range(len(recorded_data)): wav_file.writeframes(recorded_data[i])

完整示例 一个完整的示例如下

import wave

import soundcard as sc import numpy as np import time

def record_and_save(device, filename, duration=10, samplerate=16000): print(f"Starting stream recording from device: {device.name}...")

# 用于存储录制的数据 recorded_data = []

with device.recorder(samplerate, 1) as mic: try: start_time = time.time() while time.time() - start_time < duration: frames = mic.record(numframes=1024) recorded_data.append((frames * 32768).astype(np.int16).tobytes()) except KeyboardInterrupt: print("\nRecording stopped.")

# 保存为 WAV 文件 print(f"Saving recorded data to {filename}...") with wave.open(filename, mode="wb") as wav_file: wav_file.setnchannels(1) wav_file.setsampwidth(2) wav_file.setframerate(samplerate) for i in range(len(recorded_data)): wav_file.writeframes(recorded_data[i])

print(f"Recording saved to {filename}")

def main(): mics = sc.all_microphones(include_loopback=True) loopback_devices = [] loopback_devices_name = [] for i in range(len(mics)): if mics[i].isloopback is True: loopback_devices.append(mics[i]) loopback_devices_name.append(mics[i].name)

if len(loopback_devices) == 0: print("无可用的内录设备!

") exit(0) print(f"可用的内录设备有:") for i in range(len(loopback_devices)): print(f"{i}: {loopback_devices_name[i]}")

idx = input("请选择内录设备:") try: idx = int(idx) except: print("输入错误") exit(0) if idx < 0 or idx >= len(loopback_devices): print("输入错误") exit(0)

device = loopback_devices[idx]

record_and_save(device, filename="record.wav", duration=6)

if __name__ == "__main__": main()

相关文章