intxcc / pyaudio_portaudio

A fork to record speaker output with python. PyAudio with PortAudio for Windows | Extended | Loopback | WASAPI | Latest precompiled Version
MIT License
245 stars 61 forks source link

using loopback for the mic. #42

Open Maximemp2 opened 2 years ago

Maximemp2 commented 2 years ago

I've manage to use the loopback with the speaker but i was wondering, can we use loopback for the mic too? What i mean by that, i want to be able to send audio to the mic from a wav file to simulate a user speaking. It's because i have an application(Teams) that listen on the microphone.

I've try that so far and it's not working(Error : Wrong number of channel):

import pyaudio
import wave
filename = 'output.wav'
# Set chunk size of 1024 samples per data frame
chunk = 1024  
# Open the sound file 
wf = wave.open(filename, 'rb')

# Create an interface to PortAudio
p = pyaudio.PyAudio()
print(wf.getnchannels())

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()), 
    channels=wf.getnchannels(), 
    rate=wf.getframerate(), 
    output=True,
    output_device_index=7,# The mic wit WAS Host API
    as_loopback=True)

# Read data in chunks
data = wf.readframes(chunk)

# Play the sound by writing the audio data to the stream
while data != '':
    stream.write(data)
    data = wf.readframes(chunk)

# Close and terminate the stream
stream.close()
p.terminate()