1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- from fastapi import APIRouter
- import time
- from datetime import datetime
- from dotenv import load_dotenv
- from api.ttspy import txt_to_speach,download_voice
- import time
- from moviepy.editor import VideoFileClip, concatenate_videoclips,AudioFileClip
- import random
- import os
- from moviepy.editor import *
- ttsRouter = APIRouter()
- @ttsRouter.post("/tts")
- def read_root(message :str = "我在測試",type : str = "商會"):
-
- # url = txt_to_speach(message)
- start_time = time.time()
- url,text_list = txt_to_speach(message)
- # url,execution_time = download_voice(message)
-
-
- # 合併mp3跟mp4
- output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
- output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
- merge_video_with_audio(f"{os.path.split(os.path.abspath('main.py'))[0]}/{url}" , output,type)
- end_time = time.time()
- execution_time = end_time - start_time
- return {"state":"success","url": output_url ,"mp3_url" : url,"reply_time":execution_time,"text_list":text_list}
- @ttsRouter.post("/cut_video")
- def cut_video(s :int = 5,type : int = 1):
- video_path = ""
- if type == 1:
- video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
- else :
- video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/沒聲音動嘴巴2min.mp4"
- video_clip = VideoFileClip(video_path)
- video_clip = video_clip.subclip(2,2+s)
- output_url = f"static/tts/add_video{random.randint(1,25)}.mp4"
- output = os.path.split(os.path.abspath('main.py'))[0] +"/" + output_url
- video_clip.write_videofile(output, codec='libx264', audio_codec='aac')
- return {"state":"success","url": output_url}
- def merge_video_with_audio(audio_path, output_path,type : str = "商會"):
- video_path = ""
- if type == "商會":
- video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2min.mp4"
- else :
- video_path = f"{os.path.split(os.path.abspath('main.py'))[0]}/static/2.15min.mp4"
- # 讀取視頻和音頻文件
- video_clip = VideoFileClip(video_path)
- audio_clip = AudioFileClip(audio_path)
- # 截取音頻文件的長度以匹配視頻
- video_clip = video_clip.set_duration(audio_clip.duration)
- # 將音頻添加到視頻中
- final_clip = video_clip.set_audio(audio_clip)
- # 保存合併後的視頻
- final_clip.write_videofile(output_path, codec='libx264', audio_codec='aac')
- # 釋放資源
- final_clip.close()
- video_clip.close()
- audio_clip.close()
|