using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Speech.AudioFormat;
using System.Speech.Synthesis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web;

namespace RMYY_CallCenter_Api.Utility
{
    public class TtsHelper
    {
        public static string GetAudioPath(string text, string name = "")
        {
            if (!string.IsNullOrEmpty(text))
            {
                name = string.IsNullOrEmpty(name) ? text.ToMD5String() : name + "-" + text.ToMD5String();
                string filename = name + ".wav";
                string path = HttpContext.Current.Server.MapPath("..") + "\\Audio\\";
                if (!Directory.Exists(path)) Directory.CreateDirectory(path);
                string pathfile = path + filename;
                if (!File.Exists(pathfile))
                {
                    File.Create(pathfile).Dispose();
                    Task.Factory.StartNew(() =>
                    {
                        SpeechSynthesizer synth = new SpeechSynthesizer();
                        SpeechAudioFormatInfo wavFromat = new SpeechAudioFormatInfo(EncodingFormat.Pcm, 1024 * 11, 16, 1, 16000, 2, null);
                        synth.SetOutputToWaveFile(pathfile, wavFromat);
                        synth.Speak(text);
                        synth.SetOutputToNull();
                    });
                }

                return pathfile;
            }
            else
            {
                return "";
            }
        }
    }
}
