Pygame audio choppy and laggy

Viewed 330

I am currently using multiple libraries and VB virtual audio cable to pipe mic input into a virtual microphone. I am able to do this successfully but the audio in the virtual microphone is very distorted. Any help?

Code:

import sounddevice as sd
import numpy
from pygame import mixer
import pygame
from pygame._sdl2 import get_num_audio_devices, get_audio_device_name
import random
from scipy.io.wavfile import write


mixer.init() #Initialize the mixer, this will allow the next command to work
devices = [get_audio_device_name(x, 0).decode() for x in range(get_num_audio_devices(0))] #Returns playback devices
print(devices)
mixer.quit()

pygame.mixer.init(devicename='CABLE Input (VB-Audio Virtual Cable)', frequency=44100, size=32, channels=21, buffer=4)

def callback(indata, outdata, frames, time, status):
    if status:
        print(status)
    outdata[:] = indata

    number = random.randint(1,9999999999999999)

    filename = f'output/output{str(number)}.wav'
    write(filename, 44100, outdata)  # Save as uncompressed WAV file

    sound = pygame.mixer.Sound(filename) #Load the wav
    sound.play() #Play it


# For device, first number is input and second number is output
with sd.Stream(device=(3, 8), samplerate=44100, blocksize=0, latency=00.1,
                channels=2, callback=callback) as s:

    print('Recording')
    input()

Any help is appreciated.

1 Answers

I imagine the problem here is that you are writing the chunks to disk, loading again.

Also there is no need to use pygame for this, you can specify a device by name to sounddevice.Stream and you can list the devices using souddevice.query_devices.

import sounddevice as sd
import numpy


def callback(indata, outdata, frames, time, status):
    outdata[:] = indata # simply copy

print(sd.query_devices()) # I don't know your devices but you will see them here
# For device, first number is input and second number is output
with sd.Stream(device=(3, 'CABLE Input (VB-Audio Virtual Cable)'), 
               samplerate=44100, blocksize=1024,
                channels=2, callback=callback, latency=0) as s:
    input()
Related