package cn.iocoder.byzs.module.ai.service.tts;

import cn.iocoder.byzs.module.ai.dal.dataobject.tts.AiTtsDO;
import cn.iocoder.byzs.module.ai.util.tts.StreamTtsService;
import com.alibaba.nls.client.protocol.OutputFormatEnum;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.ByteArrayOutputStream;

@Service
public class AliyunTtsService {

    @Resource
    private ObjectProvider<StreamTtsService> streamTtsServiceProvider;

    public byte[] convertTextToSpeech(AiTtsDO aiTtsDO, String content) {
        StreamTtsService streamTtsService = streamTtsServiceProvider.getObject();
        try {
            // 创建音频数据缓冲区
            ByteArrayOutputStream audioOutputStream = new ByteArrayOutputStream();
            // 设置音频数据回调
            streamTtsService.setAudioDataCallback(audioData -> {
                try {
                    audioOutputStream.write(audioData);
                } catch (Exception e) {
                    throw new RuntimeException("写入音频数据失败", e);
                }
            });

            // 开始TTS语音合成
            streamTtsService.startTts(aiTtsDO, OutputFormatEnum.MP3);
            // 发送文本
            streamTtsService.sendText(content);
            // 停止TTS
            streamTtsService.stopTts();

            return audioOutputStream.toByteArray();
        } catch (Exception e) {
            throw new RuntimeException("文本转语音失败", e);
        } finally {
            // 确保资源被释放
            if (streamTtsService != null) {
                streamTtsService.stopTts();
            }
        }
    }
}