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.StreamingAliyunTtsService;
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<StreamingAliyunTtsService> streamTtsServiceProvider;

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

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

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