tts_router.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. from fastapi import APIRouter
  2. import time
  3. from datetime import datetime
  4. from dotenv import load_dotenv
  5. from api.ttspy import txt_to_speach,download_voice
  6. import time
  7. from moviepy.editor import VideoFileClip, concatenate_videoclips,AudioFileClip
  8. import random
  9. import os
  10. ttsRouter = APIRouter()
  11. @ttsRouter.post("/tts")
  12. def read_root(message :str = "我在測試",type : str = "商會"):
  13. # url = txt_to_speach(message)
  14. start_time = time.time()
  15. url,text_list = txt_to_speach(message)
  16. # url,execution_time = download_voice(message)
  17. # 合併mp3跟mp4
  18. output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
  19. output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
  20. merge_video_with_audio(f"{os.path.split(os.path.abspath('main.py'))[0]}/{url}" , output,type)
  21. end_time = time.time()
  22. execution_time = end_time - start_time
  23. return {"state":"success","url": output_url ,"mp3_url" : url,"reply_time":execution_time,"text_list":text_list}
  24. def merge_video_with_audio(audio_path, output_path,type : str = "商會"):
  25. video_path = ""
  26. if type == "商會":
  27. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2min.mp4"
  28. else :
  29. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
  30. # 讀取視頻和音頻文件
  31. video_clip = VideoFileClip(video_path)
  32. audio_clip = AudioFileClip(audio_path)
  33. # 截取音頻文件的長度以匹配視頻
  34. video_clip = video_clip.set_duration(audio_clip.duration)
  35. # 將音頻添加到視頻中
  36. final_clip = video_clip.set_audio(audio_clip)
  37. # 保存合併後的視頻
  38. final_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
  39. # 釋放資源
  40. final_clip.close()
  41. video_clip.close()
  42. audio_clip.close()