繁体   English   中英

pyaudio录音python

[英]pyaudio audio recording python

我正在尝试使用 Python 从麦克风录制音频。 我有以下代码:

import pyaudio
import wave
import threading

FORMAT = pyaudio.paInt16
CHANNELS = 2
RATE = 44100
CHUNK = 1024
WAVE_OUTPUT_FILENAME = "file.wav"

stop_ = False
audio = pyaudio.PyAudio()

stream = audio.open(format=FORMAT, channels=CHANNELS,
                    rate=RATE, input=True,
                    frames_per_buffer=CHUNK)


def stop():
    global stop_
    while True:
        if not input('Press Enter >>>'):
            print('exit')
            stop_ = True


t = threading.Thread(target=stop, daemon=True).start()
frames = []

while True:
    data = stream.read(CHUNK)
    frames.append(data)
    if stop_:
        break

stream.stop_stream()
stream.close()
audio.terminate()
waveFile = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
waveFile.setnchannels(CHANNELS)
waveFile.setsampwidth(audio.get_sample_size(FORMAT))
waveFile.setframerate(RATE)
waveFile.writeframes(b''.join(frames))
waveFile.close()

我的代码工作正常,但是当我播放我的录音时,我在最终输出文件 ( file.wav ) 中听不到任何声音。

为什么这里会出现问题,我该如何解决?

您的代码运行良好。 您面临的问题是由于管理员权限。 音频文件的数据为常量 0,因此,您无法在生成的 wav 文件中收听声音。 我想您的麦克风设备已安装并正常工作。 如果您不确定音频安装状态,则根据操作系统执行以下步骤:

MAC OS:系统偏好设置->声音->输入,在那里您可以将条形可视化为发出声音。 确保所选设备类型为内置。

在此处输入图片说明

Windos OS:声音设置和测试麦克风通过单击收听此设备,您可以稍后取消选中它,因为它会将您的声音回传到扬声器并会产生很大的噪音。

在此处输入图片说明

很可能您正在使用 Mac OS。 我遇到了类似的问题,因为我使用 Atom 编辑器来运行 python 代码。 尝试从 Mac OS 的终端(或 Power Shell,如果您使用的是 Windows)运行您的代码,(如果出现用于在 Mac OS 上访问麦克风的弹出窗口,请按 OK)。 就是这样! 您的代码将记录良好。 作为测试人员,请运行下面的代码以检查您是否可以可视化声音,并确保通过终端(无编辑器或 IDE)运行它。

import queue
import sys
from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import numpy as np
import sounddevice as sd

# Lets define audio variables
# We will use the default PC or Laptop mic to input the sound

device = 0 # id of the audio device by default
window = 1000 # window for the data
downsample = 1 # how much samples to drop
channels = [1] # a list of audio channels
interval = 30 # this is update interval in miliseconds for plot

# lets make a queue
q = queue.Queue()
# Please note that this sd.query_devices has an s in the end.
device_info =  sd.query_devices(device, 'input')
samplerate = device_info['default_samplerate']
length  = int(window*samplerate/(1000*downsample))

# lets print it 
print("Sample Rate: ", samplerate)

# Typical sample rate is 44100 so lets see.

# Ok so lets move forward

# Now we require a variable to hold the samples 

plotdata =  np.zeros((length,len(channels)))
# Lets look at the shape of this plotdata 
print("plotdata shape: ", plotdata.shape)
# So its vector of length 44100
# Or we can also say that its a matrix of rows 44100 and cols 1

# next is to make fig and axis of matplotlib plt
fig,ax = plt.subplots(figsize=(8,4))

# lets set the title
ax.set_title("PyShine")

# Make a matplotlib.lines.Line2D plot item of color green
# R,G,B = 0,1,0.29

lines = ax.plot(plotdata,color = (0,1,0.29))

# We will use an audio call back function to put the data in queue

def audio_callback(indata,frames,time,status):
    q.put(indata[::downsample,[0]])

# now we will use an another function 
# It will take frame of audio samples from the queue and update
# to the lines

def update_plot(frame):
    global plotdata
    while True:
        try: 
            data = q.get_nowait()
        except queue.Empty:
            break
        shift = len(data)
        plotdata = np.roll(plotdata, -shift,axis = 0)
        # Elements that roll beyond the last position are 
        # re-introduced 
        plotdata[-shift:,:] = data
    for column, line in enumerate(lines):
        line.set_ydata(plotdata[:,column])
    return lines
ax.set_facecolor((0,0,0))
# Lets add the grid
ax.set_yticks([0])
ax.yaxis.grid(True)

""" INPUT FROM MIC """

stream  = sd.InputStream( device = device, channels = max(channels), samplerate = samplerate, callback  = audio_callback)


""" OUTPUT """      

ani  = FuncAnimation(fig,update_plot, interval=interval,blit=True)
with stream:
    plt.show()

将此文件作为 voice.py 保存到文件夹中(比如说 AUDIO)。 然后从终端命令 cd 到 AUDIO 文件夹,然后使用以下命令执行它:

python3语音.py

或者

蟒蛇语音.py

取决于你的 python env 名称。

在此处输入图片说明

通过使用print(sd.query_devices()) ,我看到如下设备列表:

  1. Microsoft Sound Mapper - 输入,MME(2 进,0 出)
  2. 麦克风(AudioHubNano2D_V1.5,MME(2进0出)
  3. 内置麦克风(科胜讯 S、MME(2 进,0 出)
  4. ...

但是,如果我使用device = 0 ,我仍然可以从设备号 1 的 USB 麦克风接收声音。默认情况下,所有音频信号都进入声音映射器吗? 这意味着如果我使用device = 0 ,我将从所有音频输入获取所有音频信号; 如果我只想从一个特定设备输入音频,我需要选择它的编号 x 作为device = x

我还有一个问题:是否可以在一个应用程序中以不同的方式从设备 1 和 2 捕获音频信号?

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM