Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Loopback ('What u hear') recording in Python using PyAudio

Good day,

I'm trying to record my speaker output with Python using PyAudio. Currently, I'm able to record my microphone input and send this over to the 'listener'. What I'm trying to do now is create a loopback, so it will record the output from my speakers. I was able to do this with the 'Stereo Mix' from windows, but since this needs to be cross platform, there should be another way to do this.

Does anyone has some advice on how I could achieve this?

Here is my current code for recording an input stream.

import socket
import pyaudio
import wave

#record
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
RECORD_SECONDS = 40

HOST = '192.168.0.122'    # The remote host
PORT = 50007              # The same port as used by the server

recording = True

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))

p = pyaudio.PyAudio()

for i in range(0, p.get_device_count()):
    print(i, p.get_device_info_by_index(i)['name'])

device_index = int(input('Device index: '))

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

print("*recording")

frames = []

while recording:
    data  = stream.read(CHUNK)
    frames.append(data)
    s.sendall(data)

print("*done recording")

stream.stop_stream()
stream.close()
p.terminate()
s.close()

print("*closed")

Any help would be greatly appreciated!

like image 529
boortmans Avatar asked Apr 25 '14 14:04

boortmans


1 Answers

EDIT: I didn't see the cross-platform thing. Leaving this as a reference to the loopback device for Windows.

Install a virtual loopback device like [1] and select the adapter as your input device. That works for me very well.

You can check that with pyAudio like so:

>>> print p.get_device_count()
8

>>> print p.get_device_info_by_index(1)["name"]
Line 1 (Virtual Audio Cable)

So, I use 1 as my device_index.

[1] http://virtual-audio-cable.en.softonic.com/

like image 179
Peter Clause Avatar answered Oct 15 '22 09:10

Peter Clause