tts_router.py 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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. from moviepy.editor import *
  11. ttsRouter = APIRouter()
  12. @ttsRouter.post("/tts")
  13. def read_root(message :str = "我在測試",type : str = "商會"):
  14. # url = txt_to_speach(message)
  15. start_time = time.time()
  16. url,text_list = txt_to_speach(message)
  17. # url,execution_time = download_voice(message)
  18. # 合併mp3跟mp4
  19. output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
  20. output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
  21. merge_video_with_audio(f"{os.path.split(os.path.abspath('main.py'))[0]}/{url}" , output,type)
  22. end_time = time.time()
  23. execution_time = end_time - start_time
  24. return {"state":"success","url": output_url ,"mp3_url" : url,"reply_time":execution_time,"text_list":text_list}
  25. @ttsRouter.post("/cut_video")
  26. def cut_video(s :int = 5,type : int = 1):
  27. video_path = ""
  28. if type == 1:
  29. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
  30. else :
  31. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/沒聲音動嘴巴2min.mp4"
  32. video_clip = VideoFileClip(video_path)
  33. video_clip = video_clip.subclip(2,2+s)
  34. output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
  35. output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
  36. video_clip.write_videofile(output, codec='libx264', audio_codec='aac')
  37. return {"state":"success","url": output_url}
  38. def merge_video_with_audio(audio_path, output_path,type : str = "商會"):
  39. video_path = ""
  40. if type == "商會":
  41. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2min.mp4"
  42. else :
  43. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
  44. # 讀取視頻和音頻文件
  45. video_clip = VideoFileClip(video_path)
  46. audio_clip = AudioFileClip(audio_path)
  47. # 截取音頻文件的長度以匹配視頻
  48. video_clip = video_clip.set_duration(audio_clip.duration)
  49. # 將音頻添加到視頻中
  50. final_clip = video_clip.set_audio(audio_clip)
  51. # 保存合併後的視頻
  52. final_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
  53. # 釋放資源
  54. final_clip.close()
  55. video_clip.close()
  56. audio_clip.close()