【问题标题】:How to get perfect audio timing如何获得完美的音频时序
【发布时间】:2020-01-15 17:30:39
【问题描述】:

我正在尝试用这个循环节拍:

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 中完美地计时音频播放的好方法? 或者你能给我建议如何让我的代码更高效地获得最小延迟?

谢谢!

【问题讨论】:

  • 你想要多精确?

标签: python python-3.x audio pygame timing


【解决方案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 )

【讨论】:

    【解决方案2】:

    尝试对每个模式列表使用 for 循环,并根据循环中“1”的位置延迟音符播放。我的意思是尝试同时延迟所有音符。然后在最后一个音符之前开始另一个分组延迟。

    【讨论】:

      猜你喜欢
      • 2012-03-22
      • 1970-01-01
      • 1970-01-01
      • 2021-10-02
      • 2012-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-26
      相关资源
      最近更新 更多