Pygame 音频断断续续和滞后

问题描述

我目前正在使用多个库和 VB 虚拟音频电缆将麦克风输入通过管道传输到虚拟麦克风。我能够成功地做到这一点,但虚拟麦克风中的音频非常失真。有什么帮助吗?

代码

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

感谢任何帮助。

解决方法

我想这里的问题是您正在将块写入磁盘,然后再次加载。

此外,无需为此使用 pygame,您可以通过名称为 sounddevice.Stream 指定设备,并且您可以使用 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()