我正在尝试用这个循环节拍:
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 中完美地计时音频播放的好解决方案?
或者你能给我建议如何让我的代码更有效地获得最小延迟?
谢谢!
最佳答案
我认为获得这种准确度(低于 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 )
关于python - 如何获得完美的音频时序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59756722/