我需要实现可以处理抖动的音频播放器。所以我需要缓冲,因此我需要最小的缓冲区大小并知道当时缓冲区中有多少元素。
但是在 python Queue qsize() 方法中没有实现。我能做些什么呢?
class MultiprocessedAudioPlayer(object):
def __init__(self, sampling_frequency, min_buffer_size=1, max_buffer_size=10, sample_width=2):
self.p = PyAudio()
self.stream = self.p.open(format=self.p.get_format_from_width(width=sample_width), rate=sampling_frequency,
output=True, channels=1)
self.max_buffer_size = max_buffer_size
self.min_buffer_size = min_buffer_size
self.buffer = Queue(maxsize=max_buffer_size)
self.process = Process(target=self.playing)
self.process.start()
self.condition = Condition()
def schedule_to_play(self, frame):
self.condition.acquire()
if self.buffer.full():
print('Buffer is overflown')
self.condition.wait()
self.buffer.put(frame)
if self.buffer.qsize() > self.min_buffer_size:
print('Buffer length is', len(self.buffer))
self.condition.notify()
print('It is sufficient to play')
self.condition.release()
# print('frame appended buffer length is {} now'.format(self.buffer.qsize()))
def play(self, frame):
print('started playing frame at {}'.format(datetime.now()))
self.stream.write(frame, num_frames=len(frame))
print('stopped playing frame at {}'.format(datetime.now()))
def close(self):
self.stream.stop_stream()
self.stream.close()
def playing(self):
while True:
self.condition.acquire()
if self.buffer.qsize() < self.min_buffer_size:
self.condition.wait()
frame = self.buffer.popleft()
print('popping frame from buffer')
print('Buffer length is {} now'.format(len(self.buffer)))
self.condition.notify()
self.condition.release()
self.play(frame)