import time
# from kafka import KafkaConsumer
from gtts import gTTS
import subprocess
import os
import pika
credentials = pika.PlainCredentials(username='admin', password='admin')# 登录凭证
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost', port='5672', credentials=credentials))
# , virtual_host=self.virtual_host
channel = connection.channel()# 定义交换机,进行exchange声明,exchange表示交换机名称,type表示类型
channel.exchange_declare(exchange='testtopic', exchange_type='topic', durable=True)# 随机创建队列
result = channel.queue_declare('') # exclusive=True表示建立临时队列,当consumer关闭后,该队列就会被删除
queue_name = result.method.queue
# 将队列与exchange进行绑定
channel.queue_bind(exchange='testtopic',queue=queue_name, routing_key='')
print(' [*] Waiting for logs. To exit press CTRL+C')
def callback(ch,method,properties,body):
# print(ch,method,properties)
string_data = body.decode('utf-8')
print("[x] Received %r" %string_data)
paragraphs = string_data.split("xFF")
output_folder = "resource"
os.makedirs(output_folder, exist_ok=True)
filename = str(time.time())
for i, paragraph in enumerate(paragraphs):
tts = gTTS(text=paragraph, lang="zh")
output_file = os.path.join(output_folder, f"{filename}paragraph_{i+1}.mp3")
tts.save(output_file)
print(f"Generated audio for paragraph {i+1}")
# 合并所有段落的语音文件
combined_audio_file = os.path.join(output_folder, f"{filename}combined_audio.mp3")
ffmpeg_command = f"ffmpeg -i \"concat:{'|'.join([f'resource//{filename}paragraph_{i+1}.mp3' for i in range(len(paragraphs))])}\" -c copy {combined_audio_file}"
os.system(ffmpeg_command)
# ffmpeg_command = ["ffmpeg", "-i"]
# for i in range(len(paragraphs)):
# ffmpeg_command.extend([f"{filename}paragraph_{i+1}.mp3", "-i"])
# ffmpeg_command.pop() # 移除最后一个 "-i"
# ffmpeg_command.extend(["-filter_complex", f"concat=n={len(paragraphs)}:v=0:a=1", "-c:a", "aac", "-strict", "experimental", combined_audio_file])
# subprocess.run(ffmpeg_command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# print("Combined audio saved:", combined_audio_file)
# 从队列获取信息
channel.basic_consume(queue=queue_name,on_message_callback=callback,auto_ack=True)
channel.start_consuming()
注意:本文归作者所有,未经作者允许,不得转载