利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
fix(tts): stream PCM while merging pause segments
Rudy Celekli5e1140f45313
diff --git a/app/services/voice.py b/app/services/voice.pyindex f9db0e0c..496b00f7 100644--- a/app/services/voice.py+++ b/app/services/voice.py@@ -746,67 +746,76 @@ def _concat_audio_files(audio_files: list[str], output_file: str) -> bool:return Truetarget_sample_rate = 24000- combined_pcm = bytearray()ffmpeg_binary = utils.get_ffmpeg_binary()with tempfile.TemporaryDirectory() as concat_temp:- for idx, f in enumerate(audio_files):- if not os.path.exists(f) or os.path.getsize(f) == 0:- continue-- # 检查是否已经是 24000Hz 16-bit mono WAV- is_valid_pcm_wav = False- if f.lower().endswith(".wav"):- try:- with wave.open(f, "rb") as wf:- if (- wf.getframerate() == target_sample_rate- and wf.getnchannels() == 1- and wf.getsampwidth() == 2- ):- is_valid_pcm_wav = True- combined_pcm.extend(wf.readframes(wf.getnframes()))- except Exception:- is_valid_pcm_wav = False+ temp_combined_wav = os.path.join(concat_temp, "combined_master.wav")+ combined_frames = 0+ with wave.open(temp_combined_wav, "wb") as combined_wave:+ combined_wave.setnchannels(1)+ combined_wave.setsampwidth(2)+ combined_wave.setframerate(target_sample_rate)++ def append_pcm(reader):+ nonlocal combined_frames+ while chunk := reader.readframes(8192):+ combined_wave.writeframesraw(chunk)+ combined_frames += len(chunk) // 2++ for idx, f in enumerate(audio_files):+ if not os.path.exists(f) or os.path.getsize(f) == 0:+ continue- if not is_valid_pcm_wav:- # 使用 FFmpeg 将输入文件解码为 24000Hz 16-bit mono PCM WAV- pcm_wav = os.path.join(concat_temp, f"chunk_{idx}.wav")- cmd = [- ffmpeg_binary,- "-y",- "-i",- f,- "-vn",- "-ac",- "1",- "-ar",- str(target_sample_rate),- "-codec:a",- "pcm_s16le",- pcm_wav,- ]- res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)- if res.returncode == 0 and os.path.exists(pcm_wav):+ # 检查是否已经是 24000Hz 16-bit mono WAV+ is_valid_pcm_wav = False+ if f.lower().endswith(".wav"):try:- with wave.open(pcm_wav, "rb") as wf:- combined_pcm.extend(wf.readframes(wf.getnframes()))- except Exception as e:- logger.error(f"failed to read decoded pcm wav: {e}")- else:- logger.error(f"failed to decode audio chunk with ffmpeg: {res.stderr}")-- if not combined_pcm:+ with wave.open(f, "rb") as wf:+ if (+ wf.getframerate() == target_sample_rate+ and wf.getnchannels() == 1+ and wf.getsampwidth() == 2+ ):+ is_valid_pcm_wav = True+ append_pcm(wf)+ except Exception as exc:+ if is_valid_pcm_wav:+ logger.error(f"failed to stream PCM input: {exc}")+ return False+ is_valid_pcm_wav = False++ if not is_valid_pcm_wav:+ # 使用 FFmpeg 将输入文件解码为 24000Hz 16-bit mono PCM WAV+ pcm_wav = os.path.join(concat_temp, f"chunk_{idx}.wav")+ cmd = [+ ffmpeg_binary,+ "-y",+ "-i",+ f,+ "-vn",+ "-ac",+ "1",+ "-ar",+ str(target_sample_rate),+ "-codec:a",+ "pcm_s16le",+ pcm_wav,+ ]+ res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", errors="replace", check=False)+ if res.returncode == 0 and os.path.exists(pcm_wav):+ try:+ with wave.open(pcm_wav, "rb") as wf:+ append_pcm(wf)+ except Exception as e:+ logger.error(f"failed to read decoded pcm wav: {e}")+ return False+ else:+ logger.error(f"failed to decode audio chunk with ffmpeg: {res.stderr}")++ if not combined_frames:logger.error("no valid audio samples to concatenate")return False- temp_combined_wav = os.path.join(concat_temp, "combined_master.wav")- with wave.open(temp_combined_wav, "wb") as wf:- wf.setnchannels(1)- wf.setsampwidth(2)- wf.setframerate(target_sample_rate)- wf.writeframes(combined_pcm)-if output_file.lower().endswith(".wav"):shutil.copyfile(temp_combined_wav, output_file)return Truediff --git a/test/services/test_voice.py b/test/services/test_voice.pyindex 2b457096..ebd078cd 100644--- a/test/services/test_voice.py+++ b/test/services/test_voice.py@@ -1646,6 +1646,52 @@ class TestElevenLabsVoice(unittest.TestCase):self.assertNotIn("(pausa", flex_cleaned)self.assertNotIn("[pause", flex_cleaned)+ def test_concat_audio_files_reads_pcm_in_bounded_chunks(self):+ """Long pause-aware narration should not load each WAV into memory."""+ real_wave_open = vs.wave.open+ read_sizes = []++ class RecordingReader:+ def __init__(self, reader):+ self.reader = reader++ def __enter__(self):+ self.reader.__enter__()+ return self++ def __exit__(self, *args):+ return self.reader.__exit__(*args)++ def __getattr__(self, name):+ return getattr(self.reader, name)++ def readframes(self, frame_count):+ read_sizes.append(frame_count)+ return self.reader.readframes(frame_count)++ def recording_wave_open(file, mode):+ opened = real_wave_open(file, mode)+ return RecordingReader(opened) if mode == "rb" else opened++ with tempfile.TemporaryDirectory() as temp_dir:+ inputs = [str(Path(temp_dir) / f"input-{i}.wav") for i in range(2)]+ output = str(Path(temp_dir) / "joined.wav")+ for input_path in inputs:+ with real_wave_open(input_path, "wb") as writer:+ writer.setnchannels(1)+ writer.setsampwidth(2)+ writer.setframerate(24000)+ writer.writeframes(b"\x01\x00" * 20000)++ with patch.object(vs.wave, "open", side_effect=recording_wave_open):+ self.assertTrue(vs._concat_audio_files(inputs, output))++ with real_wave_open(output, "rb") as result:+ self.assertEqual(result.getnframes(), 40000)++ self.assertTrue(read_sizes)+ self.assertLessEqual(max(read_sizes), 8192)+def test_tts_with_pauses_shifts_submaker_timeline(self):"""测试包含停顿标签时,SubMaker 时间轴和音频拼接正确偏移。"""from edge_tts.srt_composer import Subtitle