package com.yeejoin.amos.speech.util;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;

/**
 * 录音文件识别极速版（提交音频文件识别，文件大小，文件时长有限制）
 * <p>
 * 音频格式：支持AAC/MP3/OPUS/WAV格式编码的音频。
 * 使用限制：支持100 MB以内且不超过2小时的音频文件的识别。
 *
 * @see SpeechRecognizerDemo
 * 时长超过2小时的文件请使用录音文件识别普通版
 *
 * <p>
 * 模型类型：8000（电话）/16000（非电话）。
 */
public class SpeechFlashRecognizerDemo {
    private final File speechFile;

    /**
     * 不支持试用版
     */
    public static void main(String[] args) {
        //String fileName = SpeechRecognizerRestfulDemo.class.getClassLoader().getResource("./nls-sample-16k.wav").getPath();
        // 重要：此处用一个本地文件来模拟发送实时流数据，实际使用时，您可以从某处实时采集或接收语音流并发送到ASR服务端。
        String fileName = "D:\\ffmpeg-4.4-full_build-shared\\bin\\test.mp3";
        String format = "mp3";
        int sampleRate = 16000;
        SpeechFlashRecognizerDemo demo = new SpeechFlashRecognizerDemo(new File(fileName));
        try {
            demo.process(SpeechUtil.getToken(), format, sampleRate);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public SpeechFlashRecognizerDemo(File speechFile) {
        this.speechFile = speechFile;
    }

    /**
     * 设置HTTPS REST POST请求
     * 1.使用http协议
     * 2.语音识别服务域名：nls-gateway.cn-shanghai.aliyuncs.com
     * 3.语音识别接口请求路径：/stream/v1/FlashRecognizer
     * 4.设置必须请求参数：appkey、token、format、sample_rate
     */
    public void process(String token, String format, int sampleRate) {
        String request = "https://nls-gateway.cn-shanghai.aliyuncs.com/stream/v1/FlashRecognizer";
        request = request + "?appkey=" + SpeechUtil.AppKey;
        request = request + "&token=" + token;
        request = request + "&format=" + format;
        request = request + "&sample_rate=" + sampleRate;

        System.out.println("Request: " + request);
        /**
         * 设置HTTPS头部字段
         *
         * 1.Content-Type：application/octet-stream
         */
        HashMap<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/octet-stream");
        /**
         * 发送HTTPS POST请求，返回服务端的响应。
         */
        long start = System.currentTimeMillis();
        String response = HttpUtil.sendPostFile(request, headers, this.speechFile);
        System.out.println("latency = " + (System.currentTimeMillis() - start) + " ms");
        if (response != null) {
            System.out.println("Response: " + response);
        } else {
            System.err.println("识别失败!");
        }
    }
}