Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
310 views
in Technique[技术] by (71.8m points)

python - Record inside sound(output from software synthesizer) not from microphone

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?

question from:https://stackoverflow.com/questions/65546433/record-inside-soundoutput-from-software-synthesizer-not-from-microphone

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...