File size: 1,645 Bytes
f615884
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import io
import os
import subprocess
import av
import numpy as np


mpv_command = ["mpv", "--no-cache", "--no-terminal", "--", "fd://0"]
mpv_process = subprocess.Popen(
    mpv_command,
    stdin=subprocess.PIPE,
    stdout=subprocess.DEVNULL,
    stderr=subprocess.DEVNULL,
)

load_chunks = False
load_chunks = os.path.exists("chunks.pkl")


audio_frames = []

# try open chunks
with open("chunks.pkl", "rb") as f:
    import pickle
    chunks = pickle.load(f)
    append = False
    for chunk in chunks:
        mpv_process.stdin.write(chunk)
        mpv_process.stdin.flush()
        # np_chunk = np.frombuffer(chunk, dtype=np.int16)
        # aa = av.AudioFrame.from_ndarray(chunk)
        try:
            if append:
                bytes_io.write(chunk)
                append = False
                bytes_io.seek(0)
            else:
                bytes_io = io.BytesIO(chunk)
            container = av.open(bytes_io, 'r')
            audio_stream = next(s for s in container.streams if s.type == 'audio')
            for frame in container.decode(audio_stream):
                # Convert the audio frame to a NumPy array
                array = frame.to_ndarray()

                # Now you can use av.AudioFrame.from_ndarray
                audio_frame = av.AudioFrame.from_ndarray(array, format='flt', layout='mono')
                audio_frame.sample_rate = 44100

                audio_frames.append(audio_frame)

        except Exception as e:
            print (e)
            append = True
            bytes_io.seek(0, io.SEEK_END)
            continue


if mpv_process.stdin:
    mpv_process.stdin.close()
mpv_process.wait()