news 2026/4/18 6:35:32

python 操作麦克风

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
python 操作麦克风

目录

查询麦克风:

测试麦克风:


查询麦克风:

import sounddevice as sd # 1. 查看所有主机API print("=== All Host APIs ===") for i, h in enumerate(sd.query_hostapis()): print(f"HostAPI {i}: {h['name']}") print("\n=== All Devices ===") # 2. 查看所有设备 for i, d in enumerate(sd.query_devices()): hostapi = sd.query_hostapis(d['hostapi']) device_type = [] if d['max_input_channels'] > 0: device_type.append("Input") if d['max_output_channels'] > 0: device_type.append("Output") print(f"Device {i}: {d['name']}") print(f" HostAPI: {hostapi['name']}") print(f" Type: {', '.join(device_type)}") print(f" Input channels: {d['max_input_channels']}") print(f" Output channels: {d['max_output_channels']}") print() # 3. 尝试使用默认设备 print("\n=== Testing Default Devices ===") print(f"Default input device: {sd.default.device[0]}") print(f"Default output device: {sd.default.device[1]}") # 4. 直接使用默认输入设备 try: def audio_callback(indata, frames, time, status): if status: print(f"Status: {status}") print(f"Audio shape: {indata.shape}") with sd.InputStream(samplerate=16000, channels=1, dtype='int16', blocksize=320, callback=audio_callback): input("🎤 Recording with default device... Press Enter to stop\n") except Exception as e: print(f"Error: {e}") # 5. 或者,列出所有输入设备 print("\n=== All Input Devices ===") input_devices = [] for i, d in enumerate(sd.query_devices()): if d['max_input_channels'] > 0: hostapi = sd.query_hostapis(d['hostapi']) input_devices.append((i, d, hostapi['name'])) print(f"Device {i}: {d['name']}") print(f" HostAPI: {hostapi['name']}") print(f" Channels: {d['max_input_channels']}") # 6. 选择一个可用的输入设备 if input_devices: print("\n=== Try using first available input device ===") mic_index = input_devices[0][0] device_info = input_devices[0][1] channels = min(1, device_info['max_input_channels']) # 使用单声道更通用 try: with sd.InputStream(device=mic_index, samplerate=16000, channels=channels, dtype='int16', blocksize=320, callback=lambda indata, frames, time, status: print(f"Audio shape: {indata.shape}")): input(f"🎤 Recording with {device_info['name']}... Press Enter to stop\n") except Exception as e: print(f"Error with device {mic_index}: {e}") else: print("No input devices found at all!")

测试麦克风:

import sounddevice as sd import numpy as np # 直接使用设备10 mic_index = 10 print("Testing microphone...") def callback(indata, frames, time, status): volume = np.linalg.norm(indata) * 10 print(f"Microphone level: {volume:.2f}", end='\r') # 尝试不同的参数组合 settings_to_try = [ {'samplerate': 16000, 'channels': 1, 'dtype': 'int16'}, {'samplerate': 44100, 'channels': 1, 'dtype': 'float32'}, {'samplerate': 48000, 'channels': 1, 'dtype': 'int16'}, ] for i, settings in enumerate(settings_to_try): print(f"\nTry {i+1}: {settings}") try: with sd.InputStream( device=mic_index, callback=callback, **settings ): input(f"Settings {i+1} working! Press Enter to stop...\n") break except Exception as e: print(f"Failed: {e}")

读取麦克风:

import sounddevice as sd import numpy as np from scipy import signal mic_index = 10 target_samplerate = 16000 # 目标采样率 original_samplerate = 44100 # 设备支持的采样率 print(f"Recording at {original_samplerate}Hz, resampling to {target_samplerate}Hz") def callback(indata, frames, time, status): """接收44100Hz音频,重采样到16000Hz""" if status: print(status) # 如果是立体声,转换为单声道 if indata.shape[1] > 1: audio = np.mean(indata, axis=1) else: audio = indata.flatten() # 重采样到16000Hz num_samples = int(len(audio) * target_samplerate / original_samplerate) resampled = signal.resample(audio, num_samples) print(f"Original: {len(audio)} samples, Resampled: {len(resampled)} samples", end='\r') with sd.InputStream(device=mic_index, samplerate=original_samplerate, channels=1, dtype='float32', callback=callback): input("Recording and resampling... Press Enter to stop\n")
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/4/13 12:52:05

任务同步效率提升300%?OpenMP 5.3最新同步机制深度剖析

第一章:任务同步效率提升300%?OpenMP 5.3新机制全景透视OpenMP 5.3 在任务调度与同步机制上实现了突破性优化,尤其在细粒度任务依赖管理方面引入了全新指令,显著降低了线程空转与锁竞争开销。实验数据显示,在高并发场景…

作者头像 李华
网站建设 2026/4/17 22:25:09

YOLOFuse RCAN 注意力增强超分模型集成测试

YOLOFuse RCAN 注意力增强超分模型集成测试 在智能安防、自动驾驶和夜间监控等实际场景中,我们常常面临一个棘手的问题:当环境光照极低、有烟雾遮挡或目标热特征微弱时,仅依赖可见光图像的目标检测系统往往会“失明”。传统YOLO系列虽然在常规…

作者头像 李华
网站建设 2026/4/17 15:48:58

YOLOFuse移动端适配展望:Android/iOS端运行可能性

YOLOFuse移动端适配展望:Android/iOS端运行可能性 在智能手机、无人机和智能穿戴设备日益成为感知终端的今天,AI模型正从“云端推理”向“本地实时处理”加速迁移。尤其在安防巡检、夜间搜救、电力运维等关键场景中,传统基于RGB图像的目标检测…

作者头像 李华
网站建设 2026/4/18 5:34:21

YOLOFuse Prometheus指标采集配置

YOLOFuse Prometheus指标采集配置 在智能安防、自动驾驶和夜间监控等现实场景中,单纯依赖可见光图像的目标检测系统常常面临低光照、雾霾遮挡或热源干扰的挑战。此时,红外(IR)图像凭借其对温度敏感的特性,能够穿透黑暗…

作者头像 李华
网站建设 2026/4/18 2:43:39

YOLOFuse在自动驾驶中的潜在应用:多传感器融合初探

YOLOFuse在自动驾驶中的潜在应用:多传感器融合初探 在城市道路夜间巡逻的自动驾驶测试车中,摄像头突然“失明”——前向可见光图像被对向车辆的远光灯完全过曝,系统几乎无法识别前方静止行人。然而,红外传感器却清晰捕捉到了人体散…

作者头像 李华
网站建设 2026/4/16 18:20:04

C语言如何实现工业控制通信加密?3个关键步骤让你系统安全性提升90%

第一章:C语言工业控制通信加密概述在工业自动化系统中,设备间的数据通信安全至关重要。C语言因其高效性和对底层硬件的直接控制能力,广泛应用于可编程逻辑控制器(PLC)、嵌入式网关和现场总线协议栈的开发中。随着工业物…

作者头像 李华