Reputation: 255
I want to get data of left and right channels from sound data in PyAudio. I have 1D shape array and don't know which of them are from channels
I tried to change the first half of data to zero. I have silence. I tried to change each second number to zero. I have silence. In documentation I saw that PyAudio has a parameter "output_channels". I think it has more than one output channel.
import pyaudio
import numpy as np
CHUNK = 102
WIDTH = 2
#CHUNK = 10404
#RATE = 192000
CHANNELS = 2
RATE = 44100
p = pyaudio.PyAudio()
stream = p.open(format=p.get_format_from_width(WIDTH),
channels=CHANNELS,
rate=RATE,
input=True,
output=True,
frames_per_buffer=CHUNK)
frames_per_buffer = 44100
data=[]
n=0
a=np.zeros(CHUNK*CHANNELS*WIDTH)
for i in range(1000):
data.append(stream.read(CHUNK))
for m in range(CHUNK):
a[m]=data[0][m]
s_0=[]
for m in range(int(CHUNK*CHANNELS*WIDTH)):
s_0.append(int(data[0][m]))
a=np.asarray(s_0)
a=a.reshape(int(CHUNK*WIDTH), 2)
a_T = np.transpose(a)
a_T[1][:] = 0
a = np.transpose(a_T)
a = a.reshape(CHUNK*CHANNELS*WIDTH)
s_2=[]
for m in range(CHUNK*CHANNELS*WIDTH):
s_2.append(int(a[m]))
sound=[bytes(s_2)]
stream.write(sound.pop(0), CHUNK)
data=[]
print('s_0')
s_0[0:20]
print('s_2')
s_2[0:20]
Sound doesn't play if I change data
Upvotes: 2
Views: 2583
Reputation: 5700
This works to get channel0 from a stereo file:
import pyaudio
import wave
import numpy as np
chunk = 1024
# open up a wave
wf = wave.open('/home/jeremy/Music/440.wav', 'rb')
swidth = wf.getsampwidth()
RATE = wf.getframerate()
# open stream
p = pyaudio.PyAudio()
channels = wf.getnchannels()
stream = p.open(format =
p.get_format_from_width(wf.getsampwidth()),
channels = channels,
rate = RATE,
output = True)
# read some data
data = wf.readframes(chunk)
while len(data) == chunk*swidth*channels:
# write data out to the audio stream
stream.write(data)
indata = np.fromstring(data, dtype='int16')
# deinterleave, select 1 channel
channel0 = indata[0::channels]
data = wf.readframes(chunk)
if data:
stream.write(data)
stream.close()
p.terminate()
Upvotes: 2