I want to write a program that allows me to play sample sounds with the computer keyboard with almost no latency.
My program:
import numpy as np
import sounddevice as sd
import soundfile as sf
import msvcrt
sd.default.latency = 'low'
samplesarray = []
def load_samples(num):
filename='sample'+str(num)+'.wav'
data, fs = sf.read(filename, dtype='float32')
sd.default.samplerate = fs
samplesarray.append(data)
return
numberofsamples=3
for i in range(numberofsamples):
load_samples(i+1)
def play_session():
while 0==0:
key = int(msvcrt.getch())
sd.play(samplesarray[key-1])
return
play_session()
The program folder contains a number of 'one shot' short samples named sample1.wav, sample2.wav, etc, for instance kick-drums or snares. In this example for simplicity only three are loaded. I can launch my current program in the terminal, and play the samples 'mapped' on my keys, which is what I want. The only problem is the latency: while not huge, it's definitely noticeable.
For playing samples live, ideally latency should be practically not perceivable (order of the tens of milliseconds).
How could I achieve this?