I record the sound by pyaudio
like this
p = pyaudio.PyAudio()
hostAPICount = p.get_host_api_count()
print("Host API Count = " + str(hostAPICount))
for i in range(p.get_device_count()):
print(p.get_device_info_by_index(i))
# check the device.
# 0 -> microphone 1-> headphone
DEVICE_INDEX = 0 #or 1
CHUNK = 1024
FORMAT = pyaudio.paInt16 # 16bit
CHANNELS = 1
RATE = 48000 # sampling frequency [Hz]
time_ = 5 # record time [s]
output_path = "./sample.wav"
stream = p.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 * time_)):
data = stream.read(CHUNK)
frames.append(data)
print("done.")
stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(output_path, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames))
wf.close()
It works well for Microphone
However I want to record the sound played in my computer.(Synthesizer Application output it uses CoreAudio on MacOX)
So I changed the device number
DEVICE_INDEX = 0
-> DEVICE_INDEX = 1
But this error message appears
OSError: [Errno -9998] Invalid number of channels
Also changed the channel
but in vain, the same message appears
CHANNELS = 1
-> CHANNELS = 2
How can I record the audio which is played from local application??
Is it possible?
I came across this problem while ago and honestly wasn't able to solve it by coding but by redirecting speaker sound to an input with https://vb-audio.com/Cable/. You just need to find the right DEVICE_INDEX
by this little check I made earlier. (I think the name of the input is still the same "CABLE Output (VB-Audio Virtual "
)
import pyaudio
p = pyaudio.PyAudio()
for i in range(p.get_device_count()):
if p.get_device_info_by_index(i)["name"] == "CABLE Output (VB-Audio Virtual ":
print(p.get_device_info_by_index(i)["index"])
p.terminate()
input("Click to finish")