既然可以将音档转为文字回传了,接下来我们可以尝试看看将收到的 Text message 转为音档去进行 Audio message 的回传,而这样的功能会使用到的套件如下。
pip install
gtts
langdetect
gtts 是 Google 的文字转语音 API,它在转换文字到语音的时候会需要两个参数,分别是文字内容以及它是什么语言。因此我们会需要用到第二个套件 langdetect 来协助我们便是该段文字是用什么语言书写的,而它的输出会是 ISO 639- 1语言代码。
而 line 再传送音档的时候,会需要输入的参数除了音档的 URL 以外,还会要求输入该音档的长度,这个长度会影响到使用者在接受到该讯息时所显示的长度,虽然这部分的数值不影响音档的运作,不过为了让使用者可以準确的知道该音档的长度,我们可以利用 AudioSegment 去取得该档案的长度。範例程式码如下。
from gtts import gTTSfrom langdetect import detectfrom pydub import AudioSegmentimport math# 转成 aac 档def trans_mp3_to_aac(filepath, filename): song = AudioSegment.from_file(filepath, "mp3") song.export("./static/" + filename + ".aac", format="mp4") # 回传音档的长度(ms) return math.ceil(song.duration_seconds)# 确认所传文字的语言language = detect(instruction)# 转档并取得长度path = "./audio/mp3/" + UserId +".mp3"output = gTTS(text=instruction, lang="zh-TW", slow=False)output.save(path)# 为了避免重複存档,用乱数来编号num = random.randint(1,99999)# 因为 line 传送音档需要 aac 格式,因此转档lon = read_audio.trans_mp3_to_aac(path, UserId + str(num))# line 长度显示以秒为单位line_bot_api.reply_message(event.reply_token, AudioSendMessage(original_content_url = ngrok_url + "/static/" + UserId + str(num) + ".aac",duration=(lon*1000)))