123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172 |
- import edge_tts
- import asyncio
- from fastapi import APIRouter
- from datetime import datetime
- from dotenv import load_dotenv
- import time
- from moviepy.editor import VideoFileClip, concatenate_videoclips,AudioFileClip
- import random
- import os
- ttsTryRouter = APIRouter()
- async def my_function(output : str,TEXT = "我在測試"):
- voice = 'zh-TW-HsiaoChenNeural'
- rate = '-4%'
- volume = '+0%'
- tts = edge_tts.Communicate(text=TEXT, voice=voice, rate=rate, volume=volume)
- await tts.save(output)
- @ttsTryRouter.post("/tts_try")
- async def read_root(message :str = "我在測試",type : str = "商會"):
-
- # url = txt_to_speach(message)
- start_time = time.time()
- # text_list = message.replace(" ","").replace(",",",").split("。")
- # text_list = [item.split(',') if len(item) > 30 else [item] for item in text_list ]
- filename = f"static/tts/mp3/output{random.randint(1,25)}.mp3"
- filenames = []
- await my_function(output =filename,TEXT = 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]}/{filename}" , output,type)
- end_time = time.time()
- execution_time = end_time - start_time
- return {"state":"success","url": output_url,"reply_time":execution_time}
- 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()
|