news 2026/10/15 20:30:41

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/10/13 10:37:04

【Java毕设全套源码+文档】基于web的二手闲置交易系统的设计与实现(丰富项目+远程调试+讲解+定制)

博主介绍:✌️码农一枚 ,专注于大学生项目实战开发、讲解和毕业🚢文撰写修改等。全栈领域优质创作者,博客之星、掘金/华为云/阿里云/InfoQ等平台优质作者、专注于Java、小程序技术领域和毕业项目实战 ✌️技术范围:&am…

作者头像 李华
网站建设 2026/10/13 10:41:38

YOLOFuse代码编辑器推荐:VSCode + Python插件组合

YOLOFuse开发实战:为什么VSCode Python插件是多模态检测的最佳搭档 在夜间监控摄像头前,一个身影悄然移动。可见光画面中,他几乎与黑暗融为一体;但在红外图像里,他的热源轮廓清晰可辨——如何让AI同时“看见”这两种信…

作者头像 李华
网站建设 2026/10/13 11:26:03

YOLOFuse私有化部署成本分析:企业级解决方案

YOLOFuse私有化部署成本分析:企业级解决方案 在智能安防、工业巡检和边境监控等关键领域,夜间或恶劣环境下的目标检测始终是技术落地的“老大难”问题。传统基于RGB图像的AI模型一旦遇到低光照、浓雾或烟尘遮挡,性能往往断崖式下降——行人识…

作者头像 李华
网站建设 2026/10/15 14:02:29

YOLOFuse Kubernetes集群部署设想:大规模推理服务化

YOLOFuse Kubernetes集群部署设想:大规模推理服务化 在城市级视频监控系统中,凌晨三点的街道上,一辆可疑车辆驶入昏暗巷口。可见光摄像头画面几乎全黑,而红外传感器却清晰捕捉到热源轮廓——但单独使用任一模态都难以准确识别车型…

作者头像 李华
网站建设 2026/10/15 11:32:52

YOLOFuse MaskTextSpotter 端到端文本识别实验

YOLOFuse MaskTextSpotter:端到端多模态文本识别的工程实践 在智能监控、自动驾驶和工业质检等现实场景中,我们常常面临一个棘手的问题:光线昏暗、烟雾弥漫或强反光环境下,传统基于可见光图像的文字识别系统频频失效。摄像头“看…

作者头像 李华
网站建设 2026/10/13 11:25:50

学长亲荐!8个AI论文网站测评,本科生毕业论文必备

学长亲荐!8个AI论文网站测评,本科生毕业论文必备 2025年AI论文工具测评:为何要选对工具? 在如今的学术写作环境中,AI工具已经成为本科生完成毕业论文的重要助手。然而,面对市场上琳琅满目的平台&#xff0c…

作者头像 李华