当前位置: 首页 > news >正文

python下麦克风设备选择和录音

import pyaudio
import threading
import wave 
import numpy  as np def audio_f2i(data, width=16):"""将浮点数音频数据转换为整数音频数据。"""data = np.array(data)return np.int16(data * (2 ** (width - 1)))def audio_i2f(data, width=16):"""将整数音频数据转换为浮点数音频数据。"""data = np.array(data)return np.float32(data / (2 ** (width - 1)))def save_wavfile(path, wave_data):"""保存音频数据为wav文件。"""with wave.open(path, 'wb') as wav_file:wav_file.setnchannels(1)wav_file.setsampwidth(2)wav_file.setframerate(16000)wav_file.writeframes(np.array(wave_data).tobytes())print(f"Successfully saved wavfile: {path} ..")# 获取麦克风设备列表
def list_devices():p = pyaudio.PyAudio()info = p.get_host_api_info_by_index(0)numdevices = info.get('deviceCount')devices = []for i in range(numdevices):if p.get_device_info_by_host_api_device_index(0, i).get('maxInputChannels') > 0:devices.append(p.get_device_info_by_host_api_device_index(0, i))p.terminate()print("Available recording devices:")devices_dict = {}for i, device in enumerate(devices):print(f"{i}: {device['name']}")devices_dict[device['name']] = ireturn devices, devices_dictdef init_device():devices, devices_dict = list_devices()device_id = int(input("请选择设备:"))print("选择设备:",devices[device_id])device = devices[device_id]  # Select the first available device, modify as neededreturn deviceclass Recorder(threading.Thread):def __init__(self,format=pyaudio.paInt16,channels=1,sample_rate=16000,frames_per_buffer=1024,device = None):super().__init__()self.daemon = Trueself._stop_event = threading.Event()self.device = deviceself.init_stream(format=format,channels=channels,sample_rate=sample_rate,frames_per_buffer=frames_per_buffer)self.waveform = []def run(self):self.waveform = []chunk_size = 1024while not self._stop_event.is_set():data = self.stream.read(chunk_size)data = np.frombuffer(data,dtype='int16')self.waveform.extend(data)self.deinit_stream()def init_stream(self,format=pyaudio.paInt16,channels=1,sample_rate=16000,frames_per_buffer=1024):self.p = pyaudio.PyAudio()self.stream = self.p.open(format=format,channels=channels,rate=sample_rate,input=True,input_device_index=self.device['index'],frames_per_buffer=frames_per_buffer)print("Initialized the stream reader successfully.")def deinit_stream(self):self.stream.stop_stream()self.stream.close()self.p.terminate()print("Deinitialized the stream reader successfully.")def stop(self):self._stop_event.set()if __name__ == "__main__":device = init_device()recorder = Recorder(device=device)input("按下任意键开始录音")recorder.start()input("按下任意键结束录音")recorder.stop()recorder.join()save_wavfile('noise.wav',recorder.waveform)
http://www.lryc.cn/news/427860.html

相关文章:

  • 云和集群有什么区别?
  • 无人机视角下的EasyCVR视频汇聚管理:构建全方位、智能化的AI视频监控网络
  • 数字影像技术是如何改变我们看待世界的方式呢?
  • Chainlit实现启动页面选择不同的LLM启动器等设置界面
  • SQL - 增、改、删
  • 怎么屏蔽电脑监控软件?企业管理者的智慧选择——精准定位,合理屏蔽,让监控软件成为助力而非障碍!
  • Linux·权限与工具-make
  • C++的序列容器——数组
  • TCC 和 XA 协议之间的区别?
  • 萌啦数据插件使用情况分析,萌啦数据插件下载
  • C++初学(13)
  • 目标检测之数据增强
  • 本地下载安装WampServer结合内网穿透配置公网地址远程访问详细教程
  • 一篇文章理清Java持久化脉络(关于JDBC、JPA、Hibernate、Spring Data JPA)
  • 【数学分析笔记】第2章第1节实数系的连续性(1)
  • Speech Synthesis (LASC11062)
  • 拟合与插值|线性最小二乘拟合|非线性最小二乘拟合|一维插值|二维插值
  • 《python语言程序设计》2018版第7章第05题几何:正n边形,一个正n边形的边都有同样的长度。角度同样 设计RegularPolygon类
  • 使用Virtio Driver实现一个计算阶乘的小程序——QEMU平台
  • 【PyCharm】配置“清华镜像”地址
  • IO器件性能评估
  • 在js中判断对象是空对象的几种方法
  • 【整理】后端接口设计和优化相关思路汇总
  • docker 部署 sql server
  • 微信云开发云存储 下载全部文件
  • 1、巡线功能实现(7路数字循迹)
  • 来了...腾讯内推的软件测试面试PDF 文档(共107页)
  • Android大脑--systemserver进程
  • python项目部署:Nginx和UWSGI认识
  • 【区块链+金融服务】农业大宗供应链线上融资平台 | FISCO BCOS应用案例