package com.gyee.frame.service.ticket;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import org.springframework.stereotype.Service;

import javax.sound.sampled.*;
import java.io.File;
import java.io.IOException;

@Service
public class SpeechService {

    private ActiveXComponent component;
    private Dispatch voice;

    private Dispatch file;// 音频文件对象
    private Dispatch audio;// 音频格式对象

    private int type = 39;// 音频的输出格式
    private int volume = 100;// 音量大小：1到100
    private int rate = 0;// 播放速度：-10到10

    /**
     * 文字 --> 声音
     * @param str
     */
    public void textToVoice(String str) {
        try {
            component = new ActiveXComponent("Sapi.SpVoice");
            voice = component.getObject();
            component.setProperty("Volume", new Variant(this.volume));
            component.setProperty("Rate", new Variant(this.rate));
            Dispatch.call(voice, "Speak", new Variant(str));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭流对，释放资源
            component.safeRelease();
            voice.safeRelease();
        }
    }

    /**
     * 文字 --> 音频文件
     * @param str
     * @param path
     */
    public boolean textToVoice(String str, String path){
        try {
            component = new ActiveXComponent("Sapi.SpVoice");
            voice = component.getObject();
            // 1 创建 文件输出对象
            component = new ActiveXComponent("Sapi.SpFileStream");
            file = component.getObject();
            // 2 创建音频流格式对象
            component = new ActiveXComponent("Sapi.SpAudioFormat");
            audio = component.getObject();
            // 3 设置 音频格式
            Dispatch.put(audio,"Type",new Variant(this.type));
            // 4 设置 输出音频
            Dispatch.putRef(file,"Format",audio);
            // 5 设置 音频文件输出路径
            Dispatch.call(file,"Open",new Variant(path),new Variant(3),new Variant(true));
            // 6 音频-->输出音频流
            Dispatch.putRef(voice,"AudioOutputStream",file);
            // 8 调整音量和语速
            Dispatch.put(voice,"Volume",new Variant(this.volume));// 设置音量
            Dispatch.put(voice,"Rate",new Variant(this.rate));// 设置速率
            // 9 语音合成（文字-->音频）
            Dispatch.call(voice,"Speak",new Variant(str));
            // 10 关闭流对，释放资源
            Dispatch.call(file,"Close");
            audio.safeRelease();
            voice.safeRelease();
            file.safeRelease();

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }

    /**
     * Java Music 播放 WAV音频文件
     * @Title: play_wav
     * @Description: 播放 WAV音频文件
     * @param path WAV文件路径
     * @throws IOException
     * @throws UnsupportedAudioFileException
     *
     */
    private void play_wav(String path) throws UnsupportedAudioFileException, IOException {
        File file=new File(path);
        if(!file.exists() || !path.toLowerCase().endsWith(".wav")) {
            throw new RuntimeException("文件不存在");
        }
        AudioInputStream stream= AudioSystem.getAudioInputStream(file);
        AudioFormat target = stream.getFormat();
        DataLine.Info dinfo = new DataLine.Info(SourceDataLine.class, target);
        SourceDataLine line = null;
        int len = -1;
        try {
            line = (SourceDataLine) AudioSystem.getLine(dinfo);
            line.open(target);
            line.start();
            byte[] buffer = new byte[1024];
            while ((len = stream.read(buffer)) > 0) {
                line.write(buffer, 0, len);
            }
            // Block等待临时数据被输出为空
            line.drain();
            // 关闭读取流
            stream.close();
            // 停止播放
            line.stop();
            line.close();
        }catch (Exception e) {
            throw new RuntimeException(e.getMessage());
        }
    }
}
