python - 如何获得完美的音频时序

标签 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:
        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/

相关文章:

algorithm - 如何在php中检测歌曲的BPM

python - 从 HTML 页面中删除样板内容

python - 如果对象是私有(private)的,则排除对象

python - PyUsb USB 条码扫描器

python - 为什么我在乘以 Numpy 乘积输出时会出现溢出错误?

python - 带单引号的字符串提取

python - 类之间共享属性 : is multi-inheritance right and "pythonic" here?

python - 有什么方法可以在不将视频保存到本地的情况下从视频URL中提取音频吗?

python - 减少运行时间、文件读取、每行的字符串操作和文件写入

javascript - 如何通过方波与音调相乘来产生节拍?