File size: 1,100 Bytes
e3af00f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import asyncio

import aiofiles
import numpy as np
import pydub


class AsyncWriter:
    def __init__(self, path):
        self.queue = asyncio.Queue(maxsize=240)
        self.path = path

    async def pipeline(self):
        try:
            async with aiofiles.open(self.path, "wb", 0) as f:
                while (bytes := await self.queue.get()) is not None:
                    await f.write(bytes)
        except:
            pass

    async def write_bytes(self, bytes):
        await self.queue.put(bytes)


class VideoAsyncWriter(AsyncWriter):
    def __init__(self, path, fps):
        super().__init__(path)
        self.fps = fps

    async def write(self, video: np.array):
        return await self.write_bytes(video.astype(np.uint8).tobytes())


class AudioAsyncWriter(AsyncWriter):
    def __init__(self, path, audio_sample_rate):
        super().__init__(path)
        self.audio_sample_rate = audio_sample_rate

    async def write(self, audio: pydub.AudioSegment):
        return await self.write_bytes(
            audio.set_frame_rate(self.audio_sample_rate).raw_data
        )