Python 如何获得完美的音频定时

Python 如何获得完美的音频定时,python,python-3.x,audio,pygame,timing,Python,Python 3.x,Audio,Pygame,Timing,我试着用这个来循环节拍: while(True): t0 = time.time() #start timing print(c) #c is the position of the pattern (e.g. kick = [1, 0, 1, 0]) if self.patterns['kick'][c] == 1: channel1.play(kick) if self.patterns['snare'][c] == 1:

我试着用这个来循环节拍:

while(True):
    t0 = time.time() #start timing

    print(c) #c is the position of the pattern (e.g. kick = [1, 0, 1, 0])

    if self.patterns['kick'][c] == 1:
        channel1.play(kick)
    if self.patterns['snare'][c] == 1:
        channel2.play(snare)

    c = (c+1)%l #increase counter/jump to start

    d = int((2400-1000*(time.time()-t0))/l) #calculates the time delay (whole loop is  2400 milliseconds); l is the pattern-lenght
    pygame.time.delay(d)            
    print (time.time() - t0)
正如你所见,我测量了整个过程的时间,然后适当地修正了我的时间延迟。但是我仍然得到+20ms的滞后

有谁知道用python播放时间音频的好方法吗? 或者你能给我一些建议,如何使我的代码更有效,以获得最小的延迟


谢谢

尝试对每个模式列表使用for循环,并根据循环中“1”的位置延迟音符播放。我的意思是试着一次把所有的音符都延迟在一起。然后,在最后一个音符之前,开始另一个分组延迟。我认为,获得这种精度(低于20毫秒)将是一个挑战

问题的一个来源可能是使用
time.time()
,它返回秒数作为大浮点数。浮点数在某些情况下并不特别精确,可能时间量的更细点正在舍入/截断

您可以尝试使用pygame时间函数,该函数以毫秒为整数返回启动后的时间。这将消除任何类型的浮点舍入/截断问题

while ( True ):
    time_start = pygame.time.get_ticks() # start timing

    # pattern_cursor is the position of the pattern (e.g. kick = [1, 0, 1, 0])
    #print( pattern_cursor )  

    if self.patterns['kick'][pattern_cursor] == 1:
        channel1.play(kick)
    if self.patterns['snare'][pattern_cursor] == 1:
        channel2.play(snare)

    # increase counter/jump to start
    pattern_cursor = ( pattern_cursor+1 ) % pattern_length 

    # calculates the time delay (whole loop is  2400 milliseconds)
    time_now   = pygame.time.get_ticks()
    time_delay = 2400-1000 * ( time_now - start_time ) / pattern_length 
    pygame.time.delay( time_delay )            
    #print( time_delay )

你想要多准确?