Create generate_audio
Browse files- generate_audio +42 -0
generate_audio
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import datetime
|
| 3 |
+
import shutil
|
| 4 |
+
import tempfile # 假設 output_file 是由 tempfile.NamedTemporaryFile 創建的
|
| 5 |
+
|
| 6 |
+
# --- 自動儲存設定 ---
|
| 7 |
+
# 定義儲存生成的語音檔案的資料夾名稱
|
| 8 |
+
SAVE_DIR = "generated_audio"
|
| 9 |
+
|
| 10 |
+
# 確保儲存資料夾存在。如果不存在,則創建它。
|
| 11 |
+
# exist_ok=True 參數表示如果資料夾已經存在,則不會引發錯誤。
|
| 12 |
+
os.makedirs(SAVE_DIR, exist_ok=True)
|
| 13 |
+
# --- 結束自動儲存設定 ---
|
| 14 |
+
|
| 15 |
+
# 假設這是在 generate_speech 函數內部,並且 output_file 已經包含了生成的語音的臨時路徑
|
| 16 |
+
# 例如:
|
| 17 |
+
# with tempfile.NamedTemporaryFile(suffix=".wav", delete=False) as fp:
|
| 18 |
+
# output_file = fp.name
|
| 19 |
+
# tts.tts_to_file(text=text, language=language, speaker_wav=speaker_wav_to_use, file_path=output_file)
|
| 20 |
+
|
| 21 |
+
# --- 自動儲存生成的語音檔案的程式碼 ---
|
| 22 |
+
# 獲取當前時間戳,用於創建唯一的檔案名
|
| 23 |
+
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 24 |
+
|
| 25 |
+
# 清理輸入文本,用於檔案名,避免特殊字元導致檔案名無效或混亂
|
| 26 |
+
# 只保留字母數字和空格,並去除首尾空格
|
| 27 |
+
safe_text = "".join(c for c in text if c.isalnum() or c.isspace()).strip()
|
| 28 |
+
if len(safe_text) > 30: # 限制檔案名中文本部分的長度,避免過長
|
| 29 |
+
safe_text = safe_text[:30] + "..." # 超過部分用省略號表示
|
| 30 |
+
|
| 31 |
+
# 組合最終儲存檔案的名稱:時間戳_語言_清理後的文本.wav
|
| 32 |
+
saved_file_name = f"{timestamp}_{language}_{safe_text}.wav"
|
| 33 |
+
|
| 34 |
+
# 組合最終儲存檔案的完整路徑:儲存目錄/檔案名
|
| 35 |
+
saved_file_path = os.path.join(SAVE_DIR, saved_file_name)
|
| 36 |
+
|
| 37 |
+
# 將生成的語音臨時檔案從其臨時位置複製到指定的儲存目錄
|
| 38 |
+
shutil.copy(output_file, saved_file_path)
|
| 39 |
+
|
| 40 |
+
# 打印儲存成功的訊息,顯示儲存的路徑
|
| 41 |
+
print(f"語音已自動儲存到:{saved_file_path}")
|
| 42 |
+
# --- 結束自動儲存程式碼 ---
|