python实时监听麦克风

2019-12-02  本文已影响0人  Colleen_oh

首先安装pyaudio

官网下载pa_stable_v190600_20161030.tgz (←或者直接点击下载)
2, 下载之后解压进入文件夹
3, 在文件夹下打开命令行输入以下命令

conda create -n listen python=3.7.1
source activate listen
$ ./configure
$ make
$ sudo make install
$ sudo apt-get install libasound-dev portaudio19-dev libportaudio2 libportaudiocpp0
$ pip install pyaudio

我看了好多。。。。安装教程,都会报错,于是我一气之下。创建了一个虚拟环境,我就不信在干净的环境下,我装不成功。。结果被我装成功了哈哈哈。
结果安装成功了,也可以成功import

实现python实时监听麦克风

代码如下:

# -*- coding: utf-8 -*-
import pyaudio
import wave
import numpy as np

def Monitor():
    CHUNK = 512
    FORMAT = pyaudio.paInt16
    CHANNELS = 1
    RATE = 48000
    RECORD_SECONDS = 5
    WAVE_OUTPUT_FILENAME = "cache.wav"
    p = pyaudio.PyAudio()
    stream = p.open(format=FORMAT,
                    channels=CHANNELS,
                    rate=RATE,
                    input=True,
                    frames_per_buffer=CHUNK)
    print("开始缓存录音")
    frames = []
    while (True):
        print('begin ')
        for i in range(0, 100):
            data = stream.read(CHUNK)
            frames.append(data)
        audio_data = np.fromstring(data, dtype=np.short)
        large_sample_count = np.sum( audio_data > 800 )
        temp = np.max(audio_data)
        if temp > 800 :
            print("检测到信号")
            print('当前阈值:',temp) 
            break
    stream.stop_stream()
    stream.close()
    p.terminate()
    wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
    wf.setnchannels(CHANNELS)
    wf.setsampwidth(p.get_sample_size(FORMAT))
    wf.setframerate(RATE)
    wf.writeframes(b''.join(frames))
    wf.close()

if __name__ == '__main__':
    Monitor()

跑成功后是下面那样

$ python get_audio.py 
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.rear
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.center_lfe
ALSA lib pcm.c:2495:(snd_pcm_open_noupdate) Unknown PCM cards.pcm.side
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
ALSA lib pcm_route.c:867:(find_matching_chmap) Found no matching channel map
开始缓存录音
begin 

参考:
https://cloud.tencent.com/developer/article/1359843

上一篇下一篇

猜你喜欢

热点阅读