respeaker / usb_4_mic_array

ReSpeaker 4 Mic Array with builtin VAD, DOA, AEC, Beamforming & NS
https://www.seeedstudio.com/ReSpeaker-Mic-Array-v2.0-p-3053.html
Apache License 2.0
141 stars 65 forks source link

Record audio channels seperately #22

Closed viduraakalanka closed 5 years ago

viduraakalanka commented 5 years ago

Hi, I have recently bought an Re-speaker Mic array v2.0 and installed 6-channel firmware. I would like to know how to record each channel separately. A python implementation would be great!!

xiongyihui commented 5 years ago

Here is it:

import sys
import pyaudio
import wave
import numpy as np

CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 6
RATE = 16000
RECORD_SECONDS = 5

pyaudio_instance = pyaudio.PyAudio()

# find the index of respeaker usb device
def find_device_index():
    found = -1

    for i in range(pyaudio_instance.get_device_count()):
        dev = pyaudio_instance.get_device_info_by_index(i)
        name = dev['name'].encode('utf-8')
        print(i, name, dev['maxInputChannels'], dev['maxOutputChannels'])
        if name.lower().find(b'respeaker') >= 0 and dev['maxInputChannels'] > 0:
            found = i
            break

    return found

device_index = find_device_index()
if device_index < 0:
    print('No ReSpeaker USB device found')
    sys.exit(1)

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

print("* recording")

frames = []

for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
    data = stream.read(CHUNK)

    # convert string to numpy array
    data_array = np.fromstring(data, dtype='int16')

    # deinterleave, select 1 channel
    channel0 = data_array[0::CHANNELS]
    #channel1 = data_array[1::CHANNELS]

    # convert numpy array to string 
    data = channel0.tostring()
    frames.append(data)

print("* done recording")

stream.stop_stream()
stream.close()
pyaudio_instance.terminate()

wf = wave.open('out.wav', 'wb')
wf.setnchannels(1)
wf.setsampwidth(pyaudio_instance.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
viduraakalanka commented 5 years ago

Thanks a lot. I was looking in the net for days on how to implement it. :-)