Trying to simulate constant byte rate. Confusion with time.sleep results

后端 未结 2 807
無奈伤痛
無奈伤痛 2020-12-22 01:49

Context

I\'m using windows 7 on my computer(the player) and linux(debian) on my college computer(the streamer), which I control using ssh.
I was trying to simu

2条回答
  •  爱一瞬间的悲伤
    2020-12-22 01:52

    Conclusion

    Thanks to @J.F.Sebastian and his code, I came to learned that:

    • Its better to use use a deadline as a time reference than create to a new reference each loop
    • Using a deadline "amortizes" the imprecision of time.sleep, oscilating a bit around the desired bitrate but resulting in an correct(and much more constant) average.
    • You only need to you use time.time() once, that means less calculations imprecisions.

    As a result, I get a constant 32000 B/s some times oscilating to 31999 and very rarely to 31745
    Now I can hear the music without any lag or jitter!

    I tried using @J.F.Sebastian implentation using only the % operator to sleep the remainder, but the KB/s oscilate strangelly, so I decided to keep the deadline implementation, which suffers imprecision by keeping adding a float value. Nevertheless, the overall result is enough for my needs.
    Thank you everyone.

    Final Code

    def read(self):
        self.deadline += 0.020  
        delay = self.deadline - time.perf_counter()
        if delay > 0:
            time.sleep(delay)
        return self._read()
    

提交回复
热议问题