我有一个 USB 麦克风和树莓派。这就是我想要做的。
我有“music.wav”文件,其中音轨设置为左声道,并且我将 USB 麦克风连接到树莓派。
当我播放“music.wav”并用麦克风说话时。我可以听到左扬声器中的音乐和左右扬声器中的麦克风声音。
我尝试了下面的代码并尝试了不同的方法,无法实现将声音限制在右侧扬声器中。
有人可以帮助我如何使用 python 语言限制仅左扬声器中的音乐和仅右扬声器中的声音吗?
下面的代码是来自两个扬声器的麦克风的声音。只需要限制在右扬声器中。请帮助!
import pyaudio
import os
import numpy as np
chunk=2800
RATE=44100
p=pyaudio.PyAudio()
#input stream setup
stream=p.open(format = pyaudio.paInt16,rate=RATE,channels=1,
input_device_index = 1, input=True, frames_per_buffer=chunk)
#the code below is from the pyAudio library documentation referenced
#below
#output stream setup
player=p.open(format = pyaudio.paInt16,rate=RATE,channels=1,
output=True, frames_per_buffer=chunk)
while True: #Used to continuously stream audio
try:
data=np.fromstring(stream.read(chunk,exception_on_overflow
=False),dtype=np.int16)
player.write(data,chunk)
except IOError:
continue
#closes streams
stream.stop_stream()
stream.close()
p.terminate
更新: 经过多次尝试后,我执行了以下代码:现在声音变得不清晰,我仍然可以进入两个扬声器......我还将“播放器” - 输出通道更改为 2.. 不走运!
import pyaudio
import os
import numpy as np
chunk=2800
RATE=44100
p=pyaudio.PyAudio()
#input stream setup
stream=p.open(format = pyaudio.paInt16,rate=RATE,channels=1,
input_device_index = 1, input=True, frames_per_buffer=chunk)
player=p.open(format = pyaudio.paInt16,rate=RATE,channels=1,
output=True,
frames_per_buffer=chunk) #tried changing channels=2
while True: #Used to continuously stream audio
try:
data=np.fromstring(stream.read(chunk,exception_on_overflow =
False),dtype=np.int16)
chunk_length = int(len(data)/2)
result = np.reshape(data, (chunk_length, 2),order='f')
#result = np.reshape(data, (chunk_length, 2))
print(result)
rightchannel=result[:, 1] #I need right
#leftchannel=result[:, 0]
print(rightchannel)
player.write(rightchannel,chunk_length)
#player.write(result,chunk)
except IOError:
continue
更新 2:
stream=p.open(format = pyaudio.paInt16,rate=RATE,channels=1,
input_device_index = 1, input=True, frames_per_buffer=chunk)
player=p.open(format = pyaudio.paInt16,rate=RATE,channels=2,
output=True,
frames_per_buffer=chunk)
while True: #Used to continuously stream audio
try:
data=np.fromstring(stream.read(chunk,exception_on_overflow =
False),dtype=np.int16)
chunk_length = int(len(data)/2)
result = np.reshape(data, (chunk_length, 2))
print(result)
rightchannel=result[:, 1] #I need right
#leftchannel=result[:, 0]
print(rightchannel)
player.write(rightchannel,chunk)
except IOError:
continue
**ERROR**>>>>
[[185 179]
[183 175]
[190 197]
...,
[156 156]
[149 144]
[145 146]]
[179 175 197 ..., 156 144 146]
Traceback (most recent call last):
File
"/home/pi/RKR_MainAudioBase/Audio_GUI_RKR/MicFuncFiles/recorder.py",
line 25, in <module>
player.write(rightchannel,chunk)
File "/usr/lib/python3/dist-packages/pyaudio.py", line 586, in write
exception_on_underflow)
ValueError: ndarray is not C-contiguous