tts_try.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import edge_tts
  2. import asyncio
  3. from fastapi import APIRouter
  4. from datetime import datetime
  5. from dotenv import load_dotenv
  6. import time
  7. from moviepy.editor import VideoFileClip, concatenate_videoclips,AudioFileClip
  8. import random
  9. import os
  10. ttsTryRouter = APIRouter()
  11. async def my_function(output : str,TEXT = "我在測試"):
  12. voice = 'zh-TW-HsiaoChenNeural'
  13. rate = '-4%'
  14. volume = '+0%'
  15. tts = edge_tts.Communicate(text=TEXT, voice=voice, rate=rate, volume=volume)
  16. await tts.save(output)
  17. @ttsTryRouter.post("/tts_try")
  18. async def read_root(message :str = "我在測試",type : str = "商會"):
  19. # url = txt_to_speach(message)
  20. start_time = time.time()
  21. # text_list = message.replace(" ","").replace(",",",").split("。")
  22. # text_list = [item.split(',') if len(item) > 30 else [item] for item in text_list ]
  23. filename = f"static/tts/mp3/output{random.randint(1,25)}.mp3"
  24. filenames = []
  25. await my_function(output =filename,TEXT = message)
  26. # url,execution_time = download_voice(message)
  27. # 合併mp3跟mp4
  28. output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
  29. output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
  30. merge_video_with_audio(f"{os.path.split(os.path.abspath('main.py'))[0]}/{filename}" , output,type)
  31. end_time = time.time()
  32. execution_time = end_time - start_time
  33. return {"state":"success","url": output_url,"reply_time":execution_time}
  34. def merge_video_with_audio(audio_path, output_path,type : str = "商會"):
  35. video_path = ""
  36. if type == "商會":
  37. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2min.mp4"
  38. else :
  39. video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
  40. # 讀取視頻和音頻文件
  41. video_clip = VideoFileClip(video_path)
  42. audio_clip = AudioFileClip(audio_path)
  43. # 截取音頻文件的長度以匹配視頻
  44. video_clip = video_clip.set_duration(audio_clip.duration)
  45. # 將音頻添加到視頻中
  46. final_clip = video_clip.set_audio(audio_clip)
  47. # 保存合併後的視頻
  48. final_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
  49. # 釋放資源
  50. final_clip.close()
  51. video_clip.close()
  52. audio_clip.close()