Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix: close audio clip after duration probe

Harry79d7870a07c8
diff --git a/app/services/video.py b/app/services/video.py
index 44f3962b..0c1d0989 100644
--- a/app/services/video.py
+++ b/app/services/video.py
@@ -264,7 +264,12 @@ def combine_videos(
threads: int = 2,
) -> str:
audio_clip = AudioFileClip(audio_file)
- audio_duration = audio_clip.duration
+ try:
+ # 这里只需要读取旁白音频时长来决定素材视频拼接长度;后续不会再使用
+ # audio_clip。读取完成后立即关闭,避免早退或异常路径泄漏文件句柄。
+ audio_duration = audio_clip.duration
+ finally:
+ close_clip(audio_clip)
logger.info(f"audio duration: {audio_duration} seconds")
logger.info(f"maximum clip duration: {max_clip_duration} seconds")
diff --git a/test/services/test_video.py b/test/services/test_video.py
index a72a681c..60add022 100644
--- a/test/services/test_video.py
+++ b/test/services/test_video.py
@@ -90,6 +90,39 @@ class TestVideoService(unittest.TestCase):
self.assertGreater(clip.duration, 0)
finally:
vd.close_clip(clip)
+
+ def test_combine_videos_closes_audio_clip_when_duration_read_fails(self):
+ """
+ `combine_videos()` 只需要读取旁白音频时长。即使读取 duration
+ 时发生异常,也必须关闭 AudioFileClip,避免文件句柄泄漏。
+ """
+
+ class _FakeAudioReader:
+ def __init__(self):
+ self.closed = False
+
+ def close(self):
+ self.closed = True
+
+ class _BrokenAudioClip:
+ def __init__(self):
+ self.reader = _FakeAudioReader()
+
+ @property
+ def duration(self):
+ raise RuntimeError("failed to read duration")
+
+ fake_audio_clip = _BrokenAudioClip()
+
+ with patch.object(vd, "AudioFileClip", return_value=fake_audio_clip):
+ with self.assertRaises(RuntimeError):
+ vd.combine_videos(
+ combined_video_path="/tmp/unused-combined.mp4",
+ video_paths=[],
+ audio_file="/tmp/unused-audio.mp3",
+ )
+
+ self.assertTrue(fake_audio_clip.reader.closed)
def test_wrap_text(self):
"""test text wrapping function"""