如何解决pyaudio录音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操作系统: 声音设置并通过单击“麦克风”来测试麦克风,您以后可以取消选中它,因为它将使您的声音回传到扬声器,并且会产生很大的噪音。
很可能您正在使用Mac OS。我遇到了类似的问题,因为我使用的是Atom编辑器来运行python代码。尝试从Mac OS(如果使用的是Windows,则为Power Shell)的终端运行代码(如果出现弹出窗口以访问Mac OS上的麦克风,请按“确定”)。而已!您的代码会记录良好。作为测试人员,请运行下面的代码以检查是否可以可视化声音,并确保通过终端(没有编辑器或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,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))
# 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 voice.py
或
python voice.py
取决于您的python env名称。
,通过使用print(sd.query_devices())
,我看到如下设备列表:
- Microsoft声音映射器-输入,MME(2进0出)
- 麦克风(AudioHubNano2D_V1.5,MME(2 in,0 out)
- 内置麦克风(Conexant S,MME(2进0出)
- ...
但是,如果我使用device = 0
,我仍然可以从USB麦克风(设备编号为1)接收声音。默认情况下,所有音频信号都到达Sound Mapper吗?这意味着如果我使用device = 0
,我将从所有音频输入中获取所有音频信号。如果我只想从一台特定设备输入音频,则需要将其数字x选择为device = x
。
我还有另一个问题:是否可以在一个应用程序中以单独的方式捕获来自设备1和2的音频信号?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。