File size: 3,361 Bytes
801f06c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb9318e
801f06c
 
eb9318e
 
801f06c
 
 
eb9318e
801f06c
 
 
 
 
 
 
 
 
eb9318e
 
801f06c
eb9318e
 
801f06c
eb9318e
801f06c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
from pathlib import Path
import subprocess
import wave
from array import array
import sys
import imageio_ffmpeg

RATE = 24000


def wav_read(path):
    with wave.open(str(path), "rb") as wav:
        if (
            wav.getnchannels() != 1
            or wav.getsampwidth() != 2
            or wav.getframerate() != RATE
        ):
            raise ValueError("Expected mono 24 kHz PCM WAV")
        samples = array("h", wav.readframes(wav.getnframes()))
        if sys.byteorder != "little":
            samples.byteswap()
        return samples


def wav_write(path, samples):
    with wave.open(str(path), "wb") as wav:
        wav.setnchannels(1)
        wav.setsampwidth(2)
        wav.setframerate(RATE)
        data = array("h", samples)
        if sys.byteorder != "little":
            data.byteswap()
        wav.writeframes(data.tobytes())


class AudioService:
    def normalize(self, source: Path, target: Path, pace=1.0):
        subprocess.run(
            [
                imageio_ffmpeg.get_ffmpeg_exe(),
                "-y",
                "-i",
                str(source),
                "-af",
                f"atempo={pace}",
                "-ac",
                "1",
                "-ar",
                str(RATE),
                "-c:a",
                "pcm_s16le",
                str(target),
            ],
            check=True,
            capture_output=True,
            timeout=90,
        )
        return target

    def align(self, turns, clips, character_ids, folder, target_seconds):
        tracks = {i: array("h") for i in character_ids}
        timeline = []
        cursor = 0
        for index, (turn, clip) in enumerate(zip(turns, clips, strict=True)):
            samples = wav_read(clip)
            length = len(samples)
            if not samples or not any(samples):
                raise ValueError("Speech provider returned empty or silent audio. Render again.")
            timeline.append(
                {**turn, "start": cursor / RATE, "end": (cursor + length) / RATE}
            )
            gap = int(turn["pause_after"] * RATE) if index < len(turns) - 1 else 0
            for identity in character_ids:
                tracks[identity].extend(
                    samples
                    if identity == turn["character_id"]
                    else array("h", [0]) * length
                )
                tracks[identity].extend(array("h", [0]) * gap)
            cursor += length + gap
        actual = cursor / RATE
        limit = min(target_seconds, 60)
        if actual > limit:
            raise ValueError(
                f"Speech is {actual:.1f}s; the maximum is {limit}s. "
                "Shorten the dialogue or increase pace and render again. Words were not changed."
            )
        length = cursor
        paths = []
        for index, identity in enumerate(character_ids):
            tracks[identity].extend(array("h", [0]) * (length - cursor))
            path = folder / f"person{index + 1}.wav"
            wav_write(path, tracks[identity])
            paths.append(path)
        mixed = array(
            "h",
            (
                max(-32768, min(32767, a + b))
                for a, b in zip(*tracks.values(), strict=True)
            ),
        )
        wav_write(folder / "mix.wav", mixed)
        return paths, timeline, length / RATE