예제 #1
2
 /// <summary>
 /// 生成FLV视频的缩略图
 /// </summary>
 /// <param name="vFileName">视频文件地址</param>
 /// <param name="FlvImgSize">宽和高参数,如:240*180</param>
 /// <returns></returns>
 public static string CatchImg(string vFileName, string FlvImgSize, string Second)
 {
     if (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName)))
         return "";
     try
     {
         string flv_img_p = vFileName.Substring(0, vFileName.Length - 4) + "_thumbs.jpg";
         string Command = " -i \"" + HttpContext.Current.Server.MapPath(vFileName) + "\" -y -f image2 -ss " + Second + " -t 0.1 -s " + FlvImgSize + " \"" + HttpContext.Current.Server.MapPath(flv_img_p) + "\"";
         System.Diagnostics.Process p = new System.Diagnostics.Process();
         p.StartInfo.FileName = @"ffmpeg.exe";
         p.StartInfo.Arguments = Command;
         p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/bin/tools/");
         //不创建进程窗口
         p.StartInfo.CreateNoWindow = true;
         p.Start();//启动线程
         p.WaitForExit();//等待完成
         p.Close();//关闭进程
         p.Dispose();//释放资源
         System.Threading.Thread.Sleep(4000);
         //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
         if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(flv_img_p)))
         {
             return flv_img_p;
         }
         return "";
     }
     catch
     {
         return "";
     }
 }
예제 #2
0
 /// <summary>
 /// 视频格式转为Flv
 /// </summary>
 /// <param name="vFileName">原视频文件地址</param>
 /// <param name="ExportName">生成后的Flv文件地址</param>
 public bool ConvertFlv(string vFileName, string ExportName)
 {
     if ((!System.IO.File.Exists(ffmpegtool)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName))))
     {
         return false;
     }
     vFileName = HttpContext.Current.Server.MapPath(vFileName);
     ExportName = HttpContext.Current.Server.MapPath(ExportName);
     string Command = " -i \"" + vFileName + "\" -y -ab 32 -ar 22050 -b 800000 -s  480*360 \"" + ExportName + "\""; //Flv格式     
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = ffmpegtool;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/tools/");
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardInput = true;
     p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.CreateNoWindow = false;
     p.Start();
     p.BeginErrorReadLine();
     p.WaitForExit();
     p.Close();
     p.Dispose();
     return true;
 }
예제 #3
0
 /// <summary>
 /// 文件加解密
 /// </summary>
 /// <param name="oFileName">原文件地址</param>
 /// <param name="EncodeOrDecode">加密或解密参数,如:-d、-f</param>
 /// <param name="Password">密码</param>
 /// <returns></returns>
 public static bool FileCrypt(string oFileName, string EncodeOrDecode, string Password)
 {
     string jpfile = HttpContext.Current.Server.MapPath("~/Bin/tools/jpfile.exe");
     if ((!System.IO.File.Exists(jpfile)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(oFileName))))
     {
         return false;
     }
     oFileName = HttpContext.Current.Server.MapPath(oFileName);
     string Command = EncodeOrDecode + " \"" + oFileName + "\" \"" + Password + "\"";
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = jpfile;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/");
     p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序 启动 线程
     //p.StartInfo.RedirectStandardInput = true;
     //p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,jpfile的所有输出信息,都为错误输出流,用 StandardOutput是捕获不到任何消息的...
     p.StartInfo.CreateNoWindow = false;//不创建进程窗口
     p.Start();//启动线程
     p.BeginErrorReadLine();//开始异步读取
     p.WaitForExit();//等待完成
     //p.StandardError.ReadToEnd();//开始同步读取
     p.Close();//关闭进程
     p.Dispose();//释放资源
     return true;
 }
예제 #4
0
 /// <summary>
 /// PDF格式转为SWF
 /// </summary>
 /// <param name="pdfPath">PDF文件地址</param>
 /// <param name="swfPath">生成后的SWF文件地址</param>
 /// <param name="beginpage">转换开始页</param>
 /// <param name="endpage">转换结束页</param>
 private static bool PDF2SWF(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
 {
     string exe = HttpContext.Current.Server.MapPath("~/Bin/tools/pdf2swf-0.9.1.exe");
     pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
     swfPath = HttpContext.Current.Server.MapPath(swfPath);
     if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath) || System.IO.File.Exists(swfPath))
     {
         return false;
     }
     StringBuilder sb = new StringBuilder();
     sb.Append(" \"" + pdfPath + "\"");
     sb.Append(" -o \"" + swfPath + "\"");
     sb.Append(" -s flashversion=9");
     if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
     sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");
     sb.Append(" -j " + photoQuality);
     string Command = sb.ToString();
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = exe;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/Bin/");
     p.StartInfo.UseShellExecute = false;
     p.StartInfo.RedirectStandardError = true;
     p.StartInfo.CreateNoWindow = false;
     p.Start();
     p.BeginErrorReadLine();
     p.WaitForExit();
     p.Close();
     p.Dispose();
     return true;
 }
예제 #5
0
 private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
 {
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.CreateNoWindow = false;
     p.StartInfo.UseShellExecute = true;
     p.StartInfo.FileName = "iexplore";
     p.StartInfo.Arguments = "http://www.chuiniudi.cn";
     p.Start();
     p.Dispose();
 }
예제 #6
0
        /// <summary> 
        /// 递归列举出指定目录的所有文件         /// </summary> 
        public static void ListFiles(FileSystemInfo info, string _rex)
        {
            if (!info.Exists) return;
            DirectoryInfo dir = info as DirectoryInfo;                 //不是目录
            if (dir == null) return;
            string _filePath = string.Empty;
            Dictionary<DateTime, string> _fs = new Dictionary<DateTime, string>();
            FileSystemInfo[] files = dir.GetFileSystemInfos(_rex + "_*.rar");
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo f = files[i] as FileInfo;                     //是文件
                if (f != null)
                {
                    //string _fn = f.Name;
                    //Regex r = new Regex("epis_.*_");
                    //string _t = r.Replace(_fn, "").Replace(".rar", "");

                    DateTime _dt = f.CreationTimeUtc;
                    _fs.Add(_dt, f.FullName);
                }
            }
            Dictionary<DateTime, string> dic1 = _fs.OrderBy(o => o.Key).ToDictionary(o => o.Key, p => p.Value);
            _filePath = dic1[dic1.Keys.Max()];
            FileInfo file = new FileInfo(_filePath);
            if (file != null)
            {
                AddFileSecurity(file.FullName, "Everyone", FileSystemRights.FullControl, AccessControlType.Allow);
                Config.DatabaseFile = file.FullName;

                System.Diagnostics.Process p = new System.Diagnostics.Process();

                try
                {
                    System.Diagnostics.ProcessStartInfo startinfo = new System.Diagnostics.ProcessStartInfo();
                    startinfo.FileName = @"WinRAR.exe";//需要启动的程序名
                    string rarPath = file.Directory.FullName;
                    startinfo.Arguments = string.Format("x -p0x00000000025203a0 {0} {1}", file.FullName, rarPath);//启动参数
                                                                                                                  //设置命令参数
                                                                                                                  //startinfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;  //隐藏 WinRAR 窗口
                    p.StartInfo = startinfo;
                    p.Start();//启动
                    p.WaitForExit(); //无限期等待进程 winrar.exe 退出
                }
                catch (Exception ex) { throw ex; }
                finally
                {
                    p.Dispose();
                    p.Close();
                }
            }
        }
예제 #7
0
        /// <summary>
        /// Execute a Commad
        /// </summary>
        public List<string> ExecuteCommand(string cmd, string args)
        {
            answer.Clear();
            System.Diagnostics.Process process = null;
            System.Diagnostics.ProcessStartInfo processStartInfo;
            processStartInfo = new System.Diagnostics.ProcessStartInfo();

            processStartInfo.FileName = cmd;
            if (System.Environment.OSVersion.Version.Major >= 6)  // Windows Vista or higher
            {
                processStartInfo.Verb = "runas";
            }

            processStartInfo.Arguments = args;
            processStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            processStartInfo.UseShellExecute = false;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.RedirectStandardError = true;
            processStartInfo.RedirectStandardInput = true;

            process = new System.Diagnostics.Process();
            process.StartInfo = processStartInfo;
            process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(process_OutputDataReceived);

            try
            {
                process.Start();

                StreamWriter streamWriter = process.StandardInput;
                process.BeginOutputReadLine();
                streamWriter.Close();
                process.WaitForExit();

                string error = process.StandardError.ReadToEnd();
                if (!error.Equals(""))
                {
                    answer.Add("Errors Found: " + error);
                }
            }
            catch (Exception ex)
            {
                answer.Add("Exception: " + ex.Message);
            }

            if (process != null)
            {
                process.Dispose();
            }

            return answer;
        }
예제 #8
0
        public void StartHamachi()
        {
            /* Pre: Hamachi not already installed
              *
              * Post: Launch Hamachi installer */
            System.Diagnostics.Process startHamachi = new System.Diagnostics.Process();
            startHamachi.EnableRaisingEvents = false;
            startHamachi.StartInfo.FileName = "hamachi.msi";
            try
            {
                startHamachi.Start();
                startHamachi.WaitForExit();
            }
            catch
            {
            }

            startHamachi.Close();
            startHamachi.Dispose();
        }
예제 #9
0
        /// <summary>
        /// 標準入力をリダイレクトしてプロセス起動。起動に失敗したら例外を投げる
        /// </summary>
        /// <param name="exePath"></param>
        /// <param name="arguments"></param>
        public static System.Diagnostics.Process StartProcessWithStdInRedirected(string exePath, string arguments)
        {
            var process = new System.Diagnostics.Process();

            try
            {
                process.StartInfo.FileName              = exePath;         //起動するファイルのパスを指定する
                process.StartInfo.Arguments             = arguments;       //コマンドライン引数を指定する
                process.StartInfo.CreateNoWindow        = true;            // コンソール・ウィンドウを開かない
                process.StartInfo.UseShellExecute       = false;           // シェル機能を使用しない
                process.StartInfo.RedirectStandardInput = true;            // 標準入力を使う
                process.Start();
                return(process);
            }
            catch (Exception)
            {
                process?.Dispose();
                throw;
            }
        }
예제 #10
0
        public void StartFBIP()
        {
            /* Pre:  ForceBindIP not already installed
              *
              * Post: Launch ForceBindIP Installer*/

            System.Diagnostics.Process startFBIP = new System.Diagnostics.Process();
            startFBIP.EnableRaisingEvents = false;
            startFBIP.StartInfo.FileName = "ForceBindIP-1.2a-Setup.exe";
            try
            {
                startFBIP.Start();
                startFBIP.WaitForExit();
            }
            catch
            {
            }
            startFBIP.Close();
            startFBIP.Dispose();
        }
예제 #11
0
 public void StartSC()
 {
     System.Diagnostics.Process startSC = new System.Diagnostics.Process();
     try
     {
         startSC.EnableRaisingEvents = false;
         startSC.StartInfo.CreateNoWindow = true;
         startSC.StartInfo.Arguments = "/c " + Argument;
         startSC.StartInfo.FileName = "CMD.exe";
         System.Threading.Thread.Sleep(1000);
         startSC.Start();
         startSC.WaitForExit();
     }
     catch
     {
         //Inform main class
         //startSC.Close();
        // startSC.Dispose();
     }
     startSC.Close();
     startSC.Dispose();
 }
예제 #12
0
        /// <summary>
        /// Method that ensures that the Node version meets the lowest required version
        /// </summary>
        /// <param name="nodeExe"></param>
        /// <param name="major"></param>
        /// <param name="minor"></param>
        /// <param name="build"></param>
        /// <returns></returns>
        public static bool EnsureVersion(string nodeExe, int major = 10, int minor = 15, int build = 3)
        {
            var sb = new StringBuilder();

            System.Diagnostics.Process process = null;
            try {
                process = new System.Diagnostics.Process();
                process.StartInfo.FileName  = nodeExe;
                process.StartInfo.Arguments = "-v";
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.CreateNoWindow         = true;
                process.OutputDataReceived       += (sender, args) => sb.AppendLine(args.Data);
                process.StartInfo.UseShellExecute = false;
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                // node doesn't use the same version format as .NET
                var nodeVersion = $"{sb.ToString().Substring(1)}.0";
                if (Version.TryParse(nodeVersion, out var result))
                {
                    if (result < new Version(major, minor, build, 0))
                    {
                        throw new InvalidOperationException($"Node version incompatible ({result})");
                    }

                    return(true);
                }
                return(false);
            }
            catch (Exception ex) {
                Log.Fatal(ex, ex.Message);
                throw;
            }
            finally {
                process?.Dispose();
            }
        }
 /// <summary>
 /// 生成FLV视频的缩略图
 /// </summary>
 /// <param name="vFileName">视频文件地址</param>
 /// <param name="FlvImgSize">宽和高参数,如:240*180</param>
 /// <returns></returns>
 public static string CatchImg(string vFileName, string FlvImgSize)
 {
     string ffmpeg = HttpContext.Current.Server.MapPath("~/tools/ffmpeg.exe");
     if ((!System.IO.File.Exists(ffmpeg)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName))))
         return "";
     try
     {
         string flv_img_p = vFileName.Substring(0, vFileName.Length - 4) + ".jpg";
         string Command = " -i \"" + HttpContext.Current.Server.MapPath(vFileName) + "\" -y -f image2 -t 0.1 -s " + FlvImgSize + " \"" + HttpContext.Current.Server.MapPath(flv_img_p) + "\"";
         System.Diagnostics.Process p = new System.Diagnostics.Process();
         p.StartInfo.FileName = ffmpeg;
         p.StartInfo.Arguments = Command;
         p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
         try
         {
             p.Start();
         }
         catch
         {
             return "";
         }
         finally
         {
             p.Close();
             p.Dispose();
         }
         System.Threading.Thread.Sleep(4000);
         //注意:图片截取成功后,数据由内存缓存写到磁盘需要时间较长,大概在3,4秒甚至更长;
         if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(flv_img_p)))
         {
             return flv_img_p;
         }
         return "";
     }
     catch
     {
         return "";
     }
 }
예제 #14
0
        /// <summary>
        /// ����Flv��Ƶ������ͼ
        /// </summary>
        /// <param name="vFileName">��Ƶ�ļ���ַ</param>
        public string CatchImg(string vFileName)
        {
            if ((!System.IO.File.Exists(ffmpegtool)) || (!System.IO.File.Exists(HttpContext.Current.Server.MapPath(vFileName)))) return "";
            try
            {
                string flv_img_p = vFileName.Substring(0, vFileName.Length - 4) + ".jpg";
                string Command = " -i " + HttpContext.Current.Server.MapPath(vFileName) + " -y -f image2 -t 0.1 -s " + sizeOfImg + " " + HttpContext.Current.Server.MapPath(flv_img_p);
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                p.StartInfo.FileName = ffmpegtool;
                p.StartInfo.Arguments = Command;
                p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
                try
                {
                    p.Start();
                }
                catch
                {
                    return "";
                }
                finally
                {
                    p.Close();
                    p.Dispose();
                }
                System.Threading.Thread.Sleep(4000);

                //ע��:ͼƬ��ȡ�ɹ���,�������ڴ滺��д��������Ҫʱ��ϳ�,�����3,4����������;
                if (System.IO.File.Exists(HttpContext.Current.Server.MapPath(flv_img_p)))
                {
                    return flv_img_p;
                }
                return "";
            }
            catch
            {
                return "";
            }
        }
예제 #15
0
 /// <summary>
 /// 视频格式转为Flv
 /// </summary>
 /// <param name="vFileName">原视频文件地址</param>
 /// <param name="WidthAndHeight">宽和高参数,如:480*360</param>
 /// <param name="ExportName">生成后的FLV文件地址</param>
 /// <returns></returns>
 public static bool Convert2Flv(string vFileName, string WidthAndHeight, string ExportName)
 {
     try
     {
         vFileName = HttpContext.Current.Server.MapPath(vFileName);
         ExportName = HttpContext.Current.Server.MapPath(ExportName);
         string Command = " -i \"" + vFileName + "\" -y -ab 32 -ar 22050 -b 800000 -s " + WidthAndHeight + " \"" + ExportName + "\""; //Flv格式
         System.Diagnostics.Process p = new System.Diagnostics.Process();
         p.StartInfo.FileName = @"ffmpeg.exe";
         p.StartInfo.Arguments = Command;
         p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath("~/bin/tools/");
         #region 方法一
         //p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序 启动 线程
         //p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,FFMPEG的所有输出信息,都为错误输出流,用 StandardOutput是捕获不到任何消息的...
         //p.StartInfo.CreateNoWindow = false;//不创建进程窗口
         //p.Start();//启动线程
         //p.BeginErrorReadLine();//开始异步读取
         //p.WaitForExit();//等待完成
         //p.Close();//关闭进程
         //p.Dispose();//释放资源
         #endregion
         #region 方法二
         p.StartInfo.CreateNoWindow = true;
         p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
         p.Start();//启动线程
         p.WaitForExit();//等待完成
         p.Close();//关闭进程
         p.Dispose();//释放资源
         #endregion
     }
     catch (System.Exception e)
     {
         throw e;
     }
     return true;
 }
예제 #16
0
        private void procTsSplitter(string encFilePath)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.TsSplitter + " ";
            p.StartInfo.Arguments += "\"" + encFilePath + "\"";
            p.StartInfo.Arguments += " -SD -1SEG -OUT ";
            p.StartInfo.Arguments += "\"" + this.TmpFolder + "\"";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();

            this.addLogList("TsSplitter処理を完了");
        }
예제 #17
0
        private void procDgIndex(string encFilePath)
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.DgIndex + " -i ";
            p.StartInfo.Arguments += "\"" + encFilePath + "\"";
            p.StartInfo.Arguments += " -om 2 -od ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + "\"";
            p.StartInfo.Arguments += " -hide -exit";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();

            this.addLogList("DGIndex処理を完了");
        }
예제 #18
0
        private void procQSVEncC()
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.Avs2pipemod + " -y4mt ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".avs\" | ";
            p.StartInfo.Arguments += this.QSVEncC + " " + this.QSVConfig;
            if (this.LogFlg == true)
            {
                p.StartInfo.Arguments += " --log ";
                p.StartInfo.Arguments += "\"" + LogFileFullPath + ".log\"";
            }
            p.StartInfo.Arguments += " -i - -o ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".264\"";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();

            this.addLogList("動画エンコード処理を完了");
        }
예제 #19
0
        public override IEnumerator Speak(Model.Wrapper wrapper)
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper);
                }
                else
                {
                    if (wrapper.Source == null)
                    {
                        Debug.LogWarning("'wrapper.Source' is null: " + wrapper);
                    }
                    else
                    {
                        yield return(null); //return to the main process (uid)

                        string application = applicationName();

                        if (System.IO.File.Exists(application))
                        {
                            string voiceName        = getVoiceName(wrapper);
                            int    calculatedRate   = calculateRate(wrapper.Rate);
                            int    calculatedVolume = calculateVolume(wrapper.Volume);

                            System.Diagnostics.Process speakToFileProcess = new System.Diagnostics.Process();

                            string outputFile = getOutputFile(wrapper.Uid);

                            //Debug.Log("Pitch: " + wrapper.Pitch + " - Rate: " + wrapper.Rate + " - Volume: " + wrapper.Volume);
                            //Debug.Log(prepareText(wrapper));

                            string args = "--speakToFile" + " \"" +
                                          prepareText(wrapper) + "\" \"" +
                                          outputFile.Replace('"', '\'') + "\" " +
                                          calculatedRate.ToString() + " " +
                                          calculatedVolume.ToString() + " \"" +
                                          voiceName.Replace('"', '\'') + '"';

                            if (Util.Config.DEBUG)
                            {
                                Debug.Log("Process arguments: " + args);
                            }

                            speakToFileProcess.StartInfo.FileName  = application;
                            speakToFileProcess.StartInfo.Arguments = args;

                            System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakToFileProcess))
                            {
                                Name = wrapper.Uid.ToString()
                            };
                            worker.Start();

                            silence = false;
                            onSpeakAudioGenerationStart(wrapper);

                            do
                            {
                                yield return(null);
                            } while (worker.IsAlive || !speakToFileProcess.HasExited);

                            if (speakToFileProcess.ExitCode == 0)
                            {
                                yield return(playAudioFile(wrapper, Util.Constants.PREFIX_FILE + outputFile, outputFile));
                            }
                            else
                            {
                                using (System.IO.StreamReader sr = speakToFileProcess.StandardError)
                                {
                                    string errorMessage = "Could not speak the text: " + wrapper + System.Environment.NewLine + "Exit code: " + speakToFileProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                                    Debug.LogError(errorMessage);
                                    onErrorInfo(wrapper, errorMessage);
                                }
                            }

                            speakToFileProcess.Dispose();
                        }
                        else
                        {
                            string errorMessage = "Could not find the TTS-wrapper: '" + application + "'";
                            Debug.LogError(errorMessage);
                            onErrorInfo(wrapper, errorMessage);
                        }
                    }
                }
            }
#else
            yield return(null);
#endif
        }
예제 #20
0
        /// <summary>
        /// Execute a shell command
        /// </summary>
        /// <param name="_FileToExecute">File/Command to execute</param>
        /// <param name="_CommandLine">Command line parameters to pass</param>
        /// <param name="_outputMessage">returned string value after executing shell command</param>
        /// <param name="_errorMessage">Error messages generated during shell execution</param>
        public static void ExecuteShellCommand(string _FileToExecute, string _CommandLine, ref string _outputMessage, ref string _errorMessage)
        {
            // Set process variable
            // Provides access to local and remote processes and enables you to start and stop local system processes.
            System.Diagnostics.Process _Process = null;
            try
            {
                _Process = new System.Diagnostics.Process();

                // invokes the cmd process specifying the command to be executed.
                string _CMDProcess = string.Format(System.Globalization.CultureInfo.InvariantCulture, @"{0}\cmd.exe", new object[] { Environment.SystemDirectory });

                // pass executing file to cmd (Windows command interpreter) as a arguments
                // /C tells cmd that we want it to execute the command that follows, and then exit.
                string _Arguments = string.Format(System.Globalization.CultureInfo.InvariantCulture, "/C \"{0}\"", new object[] { _FileToExecute });

                // pass any command line parameters for execution
                if (_CommandLine != null && _CommandLine.Length > 0)
                {
                    _Arguments += string.Format(System.Globalization.CultureInfo.InvariantCulture, " {0}", new object[] { _CommandLine, System.Globalization.CultureInfo.InvariantCulture });
                }

                // Specifies a set of values used when starting a process.
                System.Diagnostics.ProcessStartInfo _ProcessStartInfo = new System.Diagnostics.ProcessStartInfo(_CMDProcess, _Arguments);
                // sets a value indicating not to start the process in a new window.
                _ProcessStartInfo.CreateNoWindow = true;
                _ProcessStartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
                // sets a value indicating not to use the operating system shell to start the process.
                _ProcessStartInfo.UseShellExecute = false;
                // sets a value that indicates the output/input/error of an application is written to the Process.
                _ProcessStartInfo.RedirectStandardOutput = true;
                _ProcessStartInfo.RedirectStandardInput = true;
                _ProcessStartInfo.RedirectStandardError = true;
                _Process.StartInfo = _ProcessStartInfo;

                // Starts a process resource and associates it with a Process component.
                _Process.Start();

                // Instructs the Process component to wait indefinitely for the associated process to exit.
                _errorMessage = _Process.StandardError.ReadToEnd();
                _Process.WaitForExit();

                // Instructs the Process component to wait indefinitely for the associated process to exit.
                _outputMessage = _Process.StandardOutput.ReadToEnd();
                _Process.WaitForExit();
            }
            catch (Win32Exception _Win32Exception)
            {
                // Error
                Console.WriteLine("Win32 Exception caught in process: {0}", _Win32Exception.ToString());
            }
            catch (Exception _Exception)
            {
                // Error
                Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
            }
            finally
            {
                // close process and do cleanup
                _Process.Close();
                _Process.Dispose();
                _Process = null;
            }
        }
예제 #21
0
        private IEnumerator getVoices()
        {
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR) && !UNITY_WEBPLAYER
            //using (System.Diagnostics.Process voicesProcess = new System.Diagnostics.Process())
            //{

            System.Diagnostics.Process voicesProcess = new System.Diagnostics.Process();

            voicesProcess.StartInfo.FileName               = Util.Config.TTS_MACOS;
            voicesProcess.StartInfo.Arguments              = "-v '?'";
            voicesProcess.StartInfo.CreateNoWindow         = true;
            voicesProcess.StartInfo.RedirectStandardOutput = true;
            voicesProcess.StartInfo.RedirectStandardError  = true;
            voicesProcess.StartInfo.UseShellExecute        = false;
            voicesProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;

            //* Set your output and error (asynchronous) handlers
            //voicesProcess.OutputDataReceived += new DataReceivedEventHandler(speakNativeHandler);
            //voicesProcess.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);

            voicesProcess.Start();

            System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref voicesProcess, Util.Constants.DEFAULT_TTS_KILL_TIME));
            worker.Start();

            do
            {
                yield return(null);
            } while (worker.IsAlive || !voicesProcess.HasExited);

            if (voicesProcess.ExitCode == 0)
            {
                cachedVoices.Clear();

                using (System.IO.StreamReader streamReader = voicesProcess.StandardOutput)
                {
                    string reply;
                    while (!streamReader.EndOfStream)
                    {
                        reply = streamReader.ReadLine();

                        if (!string.IsNullOrEmpty(reply))
                        {
                            System.Text.RegularExpressions.Match match = sayRegex.Match(reply);

                            if (match.Success)
                            {
                                cachedVoices.Add(new Model.Voice(match.Groups[1].ToString(), match.Groups[3].ToString(), match.Groups[2].ToString().Replace('_', '-')));
                            }
                        }
                    }
                }

                if (Util.Constants.DEV_DEBUG)
                {
                    Debug.Log("Voices read: " + cachedVoices.CTDump());
                }

                //onVoicesReady();
            }
            else
            {
                using (System.IO.StreamReader sr = voicesProcess.StandardError)
                {
                    string errorMessage = "Could not get any voices: " + voicesProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                    Debug.LogError(errorMessage);
                    onErrorInfo(null, errorMessage);
                }
            }

            voicesProcess.Dispose();

            //}
#else
            yield return(null);
#endif

            onVoicesReady();
        }
예제 #22
0
        void LoadFile(string filepath, bool isReloading)
        {
            // Convert file
            var filenameWE  = System.IO.Path.GetDirectoryName(filepath) + "/" + System.IO.Path.GetFileNameWithoutExtension(filepath);
            var ext         = System.IO.Path.GetExtension(filepath).ToLower().Replace(".", "");
            var newFilepath = filenameWE + ".efkmodel";

            Effekseer.Utl.ModelInformation modelInfo = new Utl.ModelInformation();
            if (modelInfo.Load(newFilepath))
            {
                if (!isReloading)
                {
                    binding.SetAbsolutePath(filepath);
                    System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
                    return;
                }
            }
            else
            {
                // Remove invalid file
                if (System.IO.File.Exists(newFilepath))
                {
                    try
                    {
                        System.IO.File.Delete(newFilepath);
                    }
                    catch
                    {
                    }
                }
            }

            Dialog.OpenModel omd = new Dialog.OpenModel(modelInfo.Scale);

            if (ext == "fbx" || ext == "mqo")
            {
                omd.Show("");
                if (!omd.OK)
                {
                    return;
                }
            }

            if (ext == "fbx")
            {
                var  oldFilepath = filepath;
                bool doGenerate  = false;

                if (!System.IO.File.Exists(newFilepath) ||
                    System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                    modelInfo.Scale != omd.Magnification)
                {
                    doGenerate = true;
                }

                if (doGenerate)
                {
                    string appPath       = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    string converterPath = System.IO.Path.GetDirectoryName(appPath) + "/tools/fbxToEffekseerModelConverter.exe";

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.FileName  = converterPath;
                    info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                    System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                    p.WaitForExit();
                    p.Dispose();

                    if (System.IO.File.Exists(newFilepath))
                    {
                        System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                    }
                }
            }

            if (ext == "mqo")
            {
                var oldFilepath = filepath;

                bool doGenerate = false;

                if (!System.IO.File.Exists(newFilepath) ||
                    System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                    modelInfo.Scale != omd.Magnification)
                {
                    doGenerate = true;
                }

                if (doGenerate)
                {
                    string appPath       = System.Reflection.Assembly.GetExecutingAssembly().Location;
                    string converterPath = System.IO.Path.GetDirectoryName(appPath) + "/tools/mqoToEffekseerModelConverter.exe";

                    System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                    info.FileName  = converterPath;
                    info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                    System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                    p.WaitForExit();
                    p.Dispose();

                    if (System.IO.File.Exists(newFilepath))
                    {
                        System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                    }
                }
            }

            binding.SetAbsolutePath(filepath);

            System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
        }
예제 #23
0
        public override void Compile(CompilerParameters parameters)
        {
            string CSC_EXE = this.GetFrameworkPath() + @"csc.exe";

            if (CSC_EXE == null)
            {
                this.OnCompilerOutput(this, new Bamboo.CSharp.Compilers.CompilerOutputEventArgs("The .NET 1.1 Framework is not installed."));
                this.OnCompileFailed(this, System.EventArgs.Empty);
                return;
            }

            this.OnCompilerDaignosticStatus(this, new CompilerDiagnosticStatusEventArgs("CSC_EXE:" + CSC_EXE));

            System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
            processStartInfo.FileName = CSC_EXE;
            processStartInfo.RedirectStandardOutput = true;
            processStartInfo.UseShellExecute        = false;
            processStartInfo.CreateNoWindow         = true;
            processStartInfo.WorkingDirectory       = System.Environment.CurrentDirectory;



            string arguments = String.Empty;

            arguments += " /warn:4";

            if (parameters.ApplicationIcon.Length > 0)
            {
                arguments += " /win32icon:\"" + parameters.ApplicationIcon + "\"";
            }

            arguments += " /out:\"" + parameters.Assembly + "\"";

            arguments += " /target:" + parameters.Target;

            arguments += " /D:NET20";
            if (parameters.Define.Length > 0)
            {
                arguments += " /D:" + parameters.Define;
            }

            if (parameters.Doc.Length > 0)
            {
                arguments += " /doc:\"" + parameters.Doc + "\"";
            }

            if (parameters.Lib.Length > 0)
            {
                string argument = "/lib:\"" + parameters.Lib + "\"";
                this.OnCompilerDaignosticStatus(this, new CompilerDiagnosticStatusEventArgs("SET_LIB:" + argument));
                arguments += " " + argument;
            }

            if (parameters.Platform.Length > 0)
            {
                arguments += " /platform:" + parameters.Platform;
            }

            foreach (string reference in parameters.References)
            {
                string argument = "/R:\"" + reference + "\"";
                this.OnCompilerDaignosticStatus(this, new CompilerDiagnosticStatusEventArgs("ADD_REFERENCE:" + argument));
                arguments += " " + argument;
            }

            foreach (string resource in parameters.Resources)
            {
                string argument = "/resource:" + resource;
                this.OnCompilerDaignosticStatus(this, new CompilerDiagnosticStatusEventArgs("ADD_RESOURCE:" + argument));
                arguments += " " + argument;
            }

            if (parameters.Debug)
            {
                arguments += " /debug+";
                arguments += " /optimize-";
            }
            else
            {
                arguments += " /debug-";
                arguments += " /optimize+";
            }



            foreach (string source in parameters.Sources)
            {
                string argument = source;
                this.OnCompilerDaignosticStatus(this, new CompilerDiagnosticStatusEventArgs("ADD_SOURCE:" + argument));
                arguments += " " + argument;
            }


            processStartInfo.Arguments = arguments;
            System.Diagnostics.Process process = System.Diagnostics.Process.Start(processStartInfo);

            System.IO.StringWriter stringWriter = new System.IO.StringWriter();
            while (!process.HasExited)
            {
                stringWriter.Write(process.StandardOutput.ReadToEnd());
                process.WaitForExit(50);
            }
            stringWriter.Write(process.StandardOutput.ReadToEnd());
            process.Close();
            process.Dispose();



            bool hasErrors = false;

            string filename_pattern = @"([^(]+)";
            string goto_pattern     = filename_pattern + @"(\(([0-9]+),([0-9]+)\))?: ";
            string error_pattern    = @"(fatal error|error|warning) (CS[0-9]{4}): (.*)";
            string pattern          = @"^(" + goto_pattern + @")?" + error_pattern + "$";

            System.Text.RegularExpressions.Regex errorRegex = new System.Text.RegularExpressions.Regex(pattern, System.Text.RegularExpressions.RegexOptions.Compiled);

            System.IO.StringReader stringReader = new System.IO.StringReader(stringWriter.ToString());
            while (-1 != stringReader.Peek())
            {
                string output = stringReader.ReadLine();

                System.Text.RegularExpressions.MatchCollection matches = errorRegex.Matches(output);
                if (matches.Count != 0)
                {
                    System.Text.RegularExpressions.Match match = matches[0];
                    string error_file        = match.Groups[2].Value;
                    int    error_line        = (match.Groups[4].Value == "") ? 0 : Int32.Parse(match.Groups[4].Value);
                    int    error_column      = (match.Groups[5].Value == "") ? 0 : Int32.Parse(match.Groups[5].Value);
                    string error_code        = match.Groups[7].Value;
                    string error_description = match.Groups[8].Value;

                    if (match.Groups[6].Value == "error")
                    {
                        Bamboo.CSharp.Compilers.Error error = new Bamboo.CSharp.Compilers.Error(false, error_file, error_line, error_column, error_code, error_description, output);
                        parameters.Errors.Add(error);

                        this.OnCompilerError(this, new Bamboo.CSharp.Compilers.CompilerErrorEventArgs(error));
                        hasErrors = true;
                    }
                    else if (match.Groups[6].Value == "warning")
                    {
                        Bamboo.CSharp.Compilers.Error warning = new Bamboo.CSharp.Compilers.Error(true, error_file, error_line, error_column, error_code, error_description, output);
                        parameters.Errors.Add(warning);

                        this.OnCompilerError(this, new Bamboo.CSharp.Compilers.CompilerErrorEventArgs(warning));
                    }
                }



                parameters.Output.Add(output);

                this.OnCompilerOutput(this, new Bamboo.CSharp.Compilers.CompilerOutputEventArgs(output));
            }



            if (hasErrors)
            {
                this.OnCompileFailed(this, System.EventArgs.Empty);
            }
            else
            {
                this.OnCompileSucceeded(this, System.EventArgs.Empty);
            }
        }
예제 #24
0
        public override IEnumerator Generate(Model.Wrapper wrapper)
        {
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR) && !UNITY_WEBPLAYER
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'Text' is null or empty: " + wrapper);
                    //yield return null;
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    string speaker        = string.Empty;
                    int    calculatedRate = calculateRate(wrapper.Rate);

                    if (wrapper.Voice == null || string.IsNullOrEmpty(wrapper.Voice.Name))
                    {
                        if (Util.Config.DEBUG)
                        {
                            Debug.LogWarning("'Voice' or 'Voice.Name' is null! Using the OS 'default' voice.");
                        }
                    }
                    else
                    {
                        speaker = wrapper.Voice.Name;
                    }

                    string outputFile = Util.Config.AUDIOFILE_PATH + wrapper.Uid + extension;

                    //using (System.Diagnostics.Process speakToFileProcess = new System.Diagnostics.Process())
                    //{

                    System.Diagnostics.Process speakToFileProcess = new System.Diagnostics.Process();

                    string args = (string.IsNullOrEmpty(speaker) ? string.Empty : (" -v \"" + speaker.Replace('"', '\'') + '"')) +
                                  (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " -o \"" +
                                  outputFile.Replace('"', '\'') + '"' +
                                  " --file-format=AIFFLE" + " \"" +
                                  wrapper.Text.Replace('"', '\'') + '"';

                    if (Util.Config.DEBUG)
                    {
                        Debug.Log("Process argruments: " + args);
                    }

                    speakToFileProcess.StartInfo.FileName       = Util.Config.TTS_MACOS;
                    speakToFileProcess.StartInfo.Arguments      = args;
                    speakToFileProcess.StartInfo.CreateNoWindow = true;
                    //speakToFileProcess.StartInfo.RedirectStandardOutput = true;
                    speakToFileProcess.StartInfo.RedirectStandardError = true;
                    speakToFileProcess.StartInfo.UseShellExecute       = false;
                    //speakToFileProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
                    //* Set your output and error (asynchronous) handlers
                    //speakToFileProcess.OutputDataReceived += new DataReceivedEventHandler(speakNativeHandler);
                    //speakToFileProcess.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);

                    //speakToFileProcess.Start();
                    //speakToFileProcess.BeginOutputReadLine();
                    //speakToFileProcess.BeginErrorReadLine();

                    System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakToFileProcess))
                    {
                        Name = wrapper.Uid.ToString()
                    };
                    worker.Start();

                    silence = false;
                    onSpeakAudioGenerationStart(wrapper);

                    do
                    {
                        yield return(null);
                    } while (worker.IsAlive || !speakToFileProcess.HasExited);

                    if (speakToFileProcess.ExitCode == 0)
                    {
                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Text generated: " + wrapper.Text);
                        }

                        if (!string.IsNullOrEmpty(wrapper.OutputFile))
                        {
                            wrapper.OutputFile += AudioFileExtension;
                            fileCopy(outputFile, wrapper.OutputFile, Util.Config.AUDIOFILE_AUTOMATIC_DELETE);
                        }

                        if (Util.Config.AUDIOFILE_AUTOMATIC_DELETE)
                        {
                            if (System.IO.File.Exists(outputFile))
                            {
                                try
                                {
                                    System.IO.File.Delete(outputFile);
                                }
                                catch (System.Exception ex)
                                {
                                    string errorMessage = "Could not delete file '" + outputFile + "'!" + System.Environment.NewLine + ex;
                                    Debug.LogError(errorMessage);
                                    onErrorInfo(wrapper, errorMessage);
                                }
                            }
                        }
                        else
                        {
                            if (string.IsNullOrEmpty(wrapper.OutputFile))
                            {
                                wrapper.OutputFile = outputFile;
                            }
                        }
                    }
                    else
                    {
                        using (System.IO.StreamReader sr = speakToFileProcess.StandardError)
                        {
                            string errorMessage = "Could not generate the text: " + speakToFileProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                            Debug.LogError(errorMessage);
                            onErrorInfo(wrapper, errorMessage);
                        }
                    }

                    onSpeakAudioGenerationComplete(wrapper);

                    speakToFileProcess.Dispose();

                    //}
                }
            }
#else
            yield return(null);
#endif
        }
예제 #25
0
        private void getVoicesInEditor()
        {
#if UNITY_STANDALONE_OSX || UNITY_EDITOR
            System.Diagnostics.Process voicesProcess = new System.Diagnostics.Process();

            voicesProcess.StartInfo.FileName  = Util.Config.TTS_MACOS;
            voicesProcess.StartInfo.Arguments = "-v '?'";

            try
            {
                long time = System.DateTime.Now.Ticks;

                System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref voicesProcess, Util.Constants.DEFAULT_TTS_KILL_TIME));
                worker.Start();

                do
                {
                    System.Threading.Thread.Sleep(50);
                } while (worker.IsAlive || !voicesProcess.HasExited);

                if (Util.Constants.DEV_DEBUG)
                {
                    Debug.Log("Finished after: " + ((System.DateTime.Now.Ticks - time) / 10000000));
                }

                if (voicesProcess.ExitCode == 0)
                {
                    System.Collections.Generic.List <Model.Voice> voices = new System.Collections.Generic.List <Model.Voice>(100);

                    using (System.IO.StreamReader streamReader = voicesProcess.StandardOutput)
                    {
                        string reply;
                        string name;

                        while (!streamReader.EndOfStream)
                        {
                            reply = streamReader.ReadLine();

                            if (!string.IsNullOrEmpty(reply))
                            {
                                System.Text.RegularExpressions.Match match = sayRegex.Match(reply);

                                if (match.Success)
                                {
                                    name = match.Groups[1].ToString();
                                    voices.Add(new Model.Voice(match.Groups[1].ToString(), match.Groups[3].ToString(), Util.Helper.AppleVoiceNameToGender(name), "unknown", match.Groups[2].ToString().Replace('_', '-')));
                                }
                            }
                        }
                    }

                    cachedVoices = voices.OrderBy(s => s.Name).ToList();

                    if (Util.Constants.DEV_DEBUG)
                    {
                        Debug.Log("Voices read: " + cachedVoices.CTDump());
                    }
                }
                else
                {
                    using (System.IO.StreamReader sr = voicesProcess.StandardError)
                    {
                        string errorMessage = "Could not get any voices: " + voicesProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                        Debug.LogError(errorMessage);
                    }
                }
            }
            catch (System.Exception ex)
            {
                string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex;
                Debug.LogError(errorMessage);
            }

            voicesProcess.Dispose();
#endif
            onVoicesReady();
        }
예제 #26
0
        /// <summary>
        /// Executes the task.
        /// </summary>
        /// <returns></returns>
        public override bool Execute()
        {
            var exec = Path.Combine(ToolPath, "tlbexp.exe");
            var args = new List <string>();

            if (File.Exists(exec) == false)
            {
                Log.LogError("Could not find tlbexp.exe: {0}", exec);
                return(false);
            }

            // assembly name argument
            if (!string.IsNullOrEmpty(Assembly))
            {
                args.Add(Assembly);
            }

            if (!string.IsNullOrWhiteSpace(OutputPath))
            {
                args.Add("/out:" + OutputPath);
            }

            if (TlbReference != null)
            {
                foreach (var i in TlbReference)
                {
                    if (!string.IsNullOrWhiteSpace(i.ItemSpec))
                    {
                        args.Add("/tlbreference:" + i.ItemSpec);
                    }
                }
            }

            if (TlbRefPath != null)
            {
                foreach (var i in TlbRefPath)
                {
                    if (!string.IsNullOrWhiteSpace(i.ItemSpec))
                    {
                        args.Add("/tlbrefpath:" + i.ItemSpec);
                    }
                }
            }

            foreach (var i in GetAsmPath())
            {
                args.Add("/asmpath:" + i);
            }

            try
            {
                using (var proc = new System.Diagnostics.Process())
                {
                    var a = new StringBuilder();
                    var b = new StringBuilder();

                    proc.StartInfo.FileName               = exec;
                    proc.StartInfo.Arguments              = string.Join(" ", args.Select(i => EscapeArg(i)).Where(i => i != null));
                    proc.StartInfo.CreateNoWindow         = true;
                    proc.StartInfo.UseShellExecute        = false;
                    proc.StartInfo.RedirectStandardOutput = true;
                    proc.StartInfo.RedirectStandardError  = true;
                    proc.OutputDataReceived              += (s, e) => { lock (a) { a.AppendLine(e.Data); } };
                    proc.ErrorDataReceived += (s, e) => { lock (b) { b.AppendLine(e.Data); } };

                    // start process
                    Log.LogMessage("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments);
                    proc.Start();
                    proc.BeginOutputReadLine();
                    proc.BeginErrorReadLine();

                    // wait for exit or timeout
                    if (proc.WaitForExit((int)TimeSpan.FromMinutes(1).TotalMilliseconds) == false)
                    {
                        Log.LogError("tlbexp.exe took too long to respond.");
                        proc.Kill();
                    }

                    // save exit code and dispose
                    var exit = proc.ExitCode;
                    proc.Dispose();

                    if (a.Length > 0)
                    {
                        var t = a.ToString().Trim();
                        if (!string.IsNullOrEmpty(t))
                        {
                            Log.LogMessage(t);
                        }
                    }

                    if (b.Length > 0)
                    {
                        var t = b.ToString().Trim();
                        if (!string.IsNullOrEmpty(t))
                        {
                            Log.LogMessage(t);
                        }
                    }

                    // success is based on exit code
                    return(exit == 0);
                }
            }
            catch (Exception e)
            {
                Log.LogError("Exception executing TlbExp: {0}", e);
                return(false);
            }
        }
예제 #27
0
        public override void SpeakNativeInEditor(Model.Wrapper wrapper)
        {
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper);
                }
                else
                {
                    string voiceName      = getVoiceName(wrapper);
                    int    calculatedRate = calculateRate(wrapper.Rate);

                    System.Diagnostics.Process speakProcess = new System.Diagnostics.Process();

                    string args = (string.IsNullOrEmpty(voiceName) ? string.Empty : (" -v \"" + voiceName.Replace('"', '\'') + '"')) +
                                  (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " \"" +
                                  wrapper.Text.Replace('"', '\'') + '"';

                    if (Util.Config.DEBUG)
                    {
                        Debug.Log("Process arguments: " + args);
                    }

                    speakProcess.StartInfo.FileName  = Util.Config.TTS_MACOS;
                    speakProcess.StartInfo.Arguments = args;

                    System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakProcess))
                    {
                        Name = wrapper.Uid.ToString()
                    };
                    worker.Start();

                    silence = false;
                    onSpeakStart(wrapper);

                    do
                    {
                        System.Threading.Thread.Sleep(50);

                        if (silence)
                        {
                            speakProcess.Kill();
                        }
                    } while (worker.IsAlive || !speakProcess.HasExited);

                    if (speakProcess.ExitCode == 0 || speakProcess.ExitCode == -1)
                    { //0 = normal ended, -1 = killed
                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Text spoken: " + wrapper.Text);
                        }

                        onSpeakComplete(wrapper);
                    }
                    else
                    {
                        using (System.IO.StreamReader sr = speakProcess.StandardError)
                        {
                            string errorMessage = "Could not speak the text: " + wrapper + System.Environment.NewLine + "Exit code: " + speakProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                            Debug.LogError(errorMessage);
                            onErrorInfo(wrapper, errorMessage);
                        }
                    }

                    speakProcess.Dispose();
                }
            }
        }
예제 #28
0
        public override IEnumerator Generate(Model.Wrapper wrapper)
        {
#if UNITY_STANDALONE_OSX || UNITY_EDITOR
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper);
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    string voiceName      = getVoiceName(wrapper);
                    int    calculatedRate = calculateRate(wrapper.Rate);
                    string outputFile     = getOutputFile(wrapper.Uid);

                    System.Diagnostics.Process speakToFileProcess = new System.Diagnostics.Process();

                    string args = (string.IsNullOrEmpty(voiceName) ? string.Empty : (" -v \"" + voiceName.Replace('"', '\'') + '"')) +
                                  (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " -o \"" +
                                  outputFile.Replace('"', '\'') + '"' +
                                  " --file-format=AIFFLE" + " \"" +
                                  wrapper.Text.Replace('"', '\'') + '"';

                    if (Util.Config.DEBUG)
                    {
                        Debug.Log("Process arguments: " + args);
                    }

                    speakToFileProcess.StartInfo.FileName  = Util.Config.TTS_MACOS;
                    speakToFileProcess.StartInfo.Arguments = args;

                    System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakToFileProcess))
                    {
                        Name = wrapper.Uid.ToString()
                    };
                    worker.Start();

                    silence = false;
                    onSpeakAudioGenerationStart(wrapper);

                    do
                    {
                        yield return(null);
                    } while (worker.IsAlive || !speakToFileProcess.HasExited);

                    if (speakToFileProcess.ExitCode == 0)
                    {
                        processAudioFile(wrapper, outputFile);
                    }
                    else
                    {
                        using (System.IO.StreamReader sr = speakToFileProcess.StandardError)
                        {
                            string errorMessage = "Could not generate the text: " + wrapper + System.Environment.NewLine + "Exit code: " + speakToFileProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                            Debug.LogError(errorMessage);
                            onErrorInfo(wrapper, errorMessage);
                        }
                    }

                    speakToFileProcess.Dispose();
                }
            }
#else
            yield return(null);
#endif
        }
예제 #29
0
        /// <summary>
        /// Runs a program and redirects the standard output and error to the console
        /// This procedure blocks until the program is finished running
        /// </summary>
        /// <param name="program">The path to the program to run</param>
        /// <param name="arguments">Any arguments to run the program with</param>
        /// <param name="StdInput">Any Input to send to the program</param>
        ///
        /// <exception cref="System.Exception"></exception>
        public static ProgramReturnValues RunProgram(String program, String arguments, String StdInput)
        {
            ProgramReturnValues retval;

            if (program == null || program == String.Empty)
            {
                throw new ArgumentNullException("program");
            }
            if (arguments == null)
            {
                arguments = "";
            }
            if (StdInput == null)
            {
                StdInput = "";
            }
            System.Diagnostics.Process p = new System.Diagnostics.Process();
            p.StartInfo.Arguments              = arguments;
            p.StartInfo.FileName               = program;
            p.StartInfo.UseShellExecute        = false;
            p.StartInfo.ErrorDialog            = false;
            p.StartInfo.RedirectStandardOutput = true;
            if (StdInput != "")
            {
                p.StartInfo.RedirectStandardInput = true;
            }

            System.IO.StreamReader sro = null;
            System.IO.StreamWriter swi = null;
            try
            {
                p.Start();
                if (StdInput != "")
                {
                    swi = p.StandardInput;
                    swi.Write(StdInput);
                    swi.Flush();
                    swi.Close();
                    swi.Dispose();
                    swi = null;
                }
                sro = p.StandardOutput;
                p.WaitForExit();

                retval.StdOutput = sro.ReadToEnd();
                retval.ExitCode  = p.ExitCode;
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (swi != null)
                {
                    swi.Close();
                    swi.Dispose();
                }
                if (sro != null)
                {
                    sro.Close();
                    sro.Dispose();
                }
                p.Close();
                p.Dispose();
            }
            return(retval);
        }
예제 #30
0
 /// <summary>
 /// PDF格式转为SWF
 /// </summary>
 /// <param name="pdfPath">原视频文件地址,如/a/b/c.pdf</param>
 /// <param name="swfPath">生成后的FLV文件地址,如/a/b/c.swf</param>
 /// <param name="beginpage">转换开始页</param>
 /// <param name="endpage">转换结束页</param>
 /// <param name="photoQuality"></param>
 /// <returns></returns>
 public static bool PDF2Swf(string pdfPath, string swfPath, int beginpage, int endpage, int photoQuality)
 {
     const string tooldir = "~/Utils/PDFtoSWF/";//PDFtoSWF工具目录地址
     string exe = HttpContext.Current.Server.MapPath(tooldir + "pdf2swf.exe");
     pdfPath = HttpContext.Current.Server.MapPath(pdfPath);
     swfPath = HttpContext.Current.Server.MapPath(swfPath);
     if (!System.IO.File.Exists(exe) || !System.IO.File.Exists(pdfPath))
     {
         return false;
     }
     if (System.IO.File.Exists(swfPath))
         System.IO.File.Delete(swfPath);
     StringBuilder sb = new StringBuilder();
     sb.Append(" \"" + pdfPath + "\"");//input
     sb.Append(" -o \"" + swfPath + "\"");//output
     //sb.Append(" -z");
     sb.Append(" -s flashversion=9");//flash version
     //sb.Append(" -s disablelinks");//禁止PDF里面的链接
     if (endpage > GetPageCount(pdfPath)) endpage = GetPageCount(pdfPath);
     sb.Append(" -p " + "\"" + beginpage + "" + "-" + endpage + "\"");//page range
     sb.Append(" -j " + photoQuality);//SWF中的图片质量
     string Command = sb.ToString();
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = exe;
     p.StartInfo.Arguments = Command;
     p.StartInfo.WorkingDirectory = HttpContext.Current.Server.MapPath(tooldir);
     p.StartInfo.UseShellExecute = false;//不使用操作系统外壳程序 启动 线程
     //p.StartInfo.RedirectStandardInput = true;
     //p.StartInfo.RedirectStandardOutput = true;
     p.StartInfo.RedirectStandardError = true;//把外部程序错误输出写到StandardError流中(这个一定要注意,pdf2swf-0.9.1.exe的所有输出信息,都为错误输出流,用 StandardOutput是捕获不到任何消息的...
     p.StartInfo.CreateNoWindow = true;//不创建进程窗口
     p.Start();//启动线程
     p.BeginErrorReadLine();//开始异步读取
     p.WaitForExit();//等待完成
     //p.StandardError.ReadToEnd();//开始同步读取
     p.Close();//关闭进程
     p.Dispose();//释放资源
     if (!System.IO.File.Exists(swfPath))
         return false;
     else
         return true;
 }
예제 #31
0
        private void getVoicesInEditor()
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
            string application = applicationName();

            if (System.IO.File.Exists(application))
            {
                System.Diagnostics.Process voicesProcess = new System.Diagnostics.Process();

                voicesProcess.StartInfo.FileName  = application;
                voicesProcess.StartInfo.Arguments = "--voices";

                try
                {
                    long time = System.DateTime.Now.Ticks;

                    System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref voicesProcess, Util.Constants.DEFAULT_TTS_KILL_TIME));
                    worker.Start();

                    do
                    {
                        System.Threading.Thread.Sleep(50);
                    } while (worker.IsAlive || !voicesProcess.HasExited);

                    if (Util.Constants.DEV_DEBUG)
                    {
                        Debug.Log("Finished after: " + ((System.DateTime.Now.Ticks - time) / 10000000));
                    }

                    if (voicesProcess.ExitCode == 0)
                    {
                        System.Collections.Generic.List <Model.Voice> voices = new System.Collections.Generic.List <Model.Voice>();

                        using (System.IO.StreamReader streamReader = voicesProcess.StandardOutput)
                        {
                            string reply;
                            while (!streamReader.EndOfStream)
                            {
                                reply = streamReader.ReadLine();

                                if (!string.IsNullOrEmpty(reply))
                                {
                                    if (reply.StartsWith(idVoice))
                                    {
                                        string[] splittedString = reply.Split(splitChar, System.StringSplitOptions.RemoveEmptyEntries);

                                        if (splittedString.Length == 6)
                                        {
                                            voices.Add(new Model.Voice(splittedString[1], splittedString[2], Util.Helper.StringToGender(splittedString[3]), splittedString[4], splittedString[5]));
                                        }
                                        else
                                        {
                                            Debug.LogWarning("Voice is invalid: " + reply);
                                        }
                                        //                     } else if(reply.Equals("@DONE") || reply.Equals("@COMPLETED")) {
                                        //                        complete = true;
                                    }
                                }
                            }
                        }

                        cachedVoices = voices.OrderBy(s => s.Name).ToList();

                        if (Util.Constants.DEV_DEBUG)
                        {
                            Debug.Log("Voices read: " + cachedVoices.CTDump());
                        }
                    }
                    else
                    {
                        using (System.IO.StreamReader sr = voicesProcess.StandardError)
                        {
                            string errorMessage = "Could not get any voices: " + voicesProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                            Debug.LogError(errorMessage);
                        }
                    }
                }
                catch (System.Exception ex)
                {
                    string errorMessage = "Could not get any voices!" + System.Environment.NewLine + ex;
                    Debug.LogError(errorMessage);
                }

                voicesProcess.Dispose();
            }
            else
            {
                string errorMessage = "Could not find the TTS-wrapper: '" + application + "'";
                Debug.LogError(errorMessage);
            }
#endif

            onVoicesReady();
        }
예제 #32
0
        static void Main(string[] args)
        {
            //Effie2017.App.Gen_GeneralUseValueList generalUseValueList = Effie2017.App.Gen_GeneralUseValueList.GetGen_GeneralUseValueList("AWSLastSync");
            DeleteFolder("TempZip");
            DeleteFolder("EntryUpload/EntryForm/");

            var entryList = EntryList.GetEntryList(Guid.Empty, Guid.Empty, "", "OK").ToList();

            foreach (Entry entry in entryList)
            {
                GenerateEF(entry);
                string multiSingle      = "";
                string productSpecialty = "";
                string cat = "";

                if (entry.CategoryMarket == "MM")
                {
                    multiSingle = "Multi Market";
                }
                else if (entry.CategoryMarket == "SM")
                {
                    multiSingle = "Single Market";
                }

                if (entry.CategoryPS == "PSC")
                {
                    productSpecialty = "Product & Services Category";
                }
                else if (entry.CategoryPS == "SC")
                {
                    productSpecialty = "Specialty Category";
                }

                cat = entry.CategoryPSDetail.Replace("/", "");

                CopyAll(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\Authorisation\\" + entry.Id.ToString() + "\\", System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\");
                CopyAll(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\Case\\" + entry.Id.ToString() + "\\", System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\");
                CopyAll(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\Creative\\" + entry.Id.ToString() + "\\", System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\");
                //CopyAll(System.Configuration.ConfigurationManager.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\Entry\\" + entry.Id.ToString() + "\\", System.Configuration.ConfigurationManager.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\");
                CopyAll(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\EntryForm\\" + entry.Id.ToString() + "\\", System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\");

                CopySingle(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "EntryUpload\\CreativeVideo\\" + entry.Serial.ToString() + "_CreativeMaterials_Video.mp4", System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\" + multiSingle + "\\" + productSpecialty + "\\" + cat + "\\" + entry.Serial + "\\" + entry.Serial.ToString() + "_CreativeMaterials_Video.mp4");
            }

            //preparing zipping program (7-zip)
            System.Diagnostics.Process Proc = new System.Diagnostics.Process();

            Proc.StartInfo.WorkingDirectory = System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "CompressorProgram\\";
            Proc.StartInfo.Arguments        = "a \"" + System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export.zip\" \"" + System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export\\*\"";
            Proc.StartInfo.FileName         = "7za.exe";

            //zipping files
            try
            {
                Proc.Start();
                Proc.WaitForExit();

                if (Proc.ExitCode == 0) //SUCCESSED
                {
                    //cleaning temp
                    if (Directory.Exists(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export"))
                    {
                        Directory.Delete(System.Configuration.ConfigurationSettings.AppSettings["storagePhysicalPath"].ToString() + "TempZip\\Files Export", true);
                    }

                    //Response.Redirect(System.Configuration.ConfigurationManager.AppSettings["storageVirtualPath"].ToString() + "TempZip/Files Export.zip", true);
                }
                else
                {
                    //Response.Write(Proc.ExitCode.ToString());
                    return;
                }

                Proc.Dispose();
            }
            catch (Exception exp)
            {
                //Response.Write(exp.Message);
                return;
            }

            //DeleteFolder("EntryUpload/EntryForm/");
        }
예제 #33
0
        /*
         *      private void outputDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
         *      {
         *          Debug.Log(e.Data);
         *      }
         *
         *      private void errorDataReceived(object sender, System.Diagnostics.DataReceivedEventArgs e)
         *      {
         *          Debug.LogError(e.Data);
         *      }
         */

        #endregion


        #region Editor-only methods

#if UNITY_EDITOR
        public override void GenerateInEditor(Model.Wrapper wrapper)
        {
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper);
                }
                else
                {
                    string application = applicationName();

                    if (System.IO.File.Exists(application))
                    {
                        string voiceName        = getVoiceName(wrapper);
                        int    calculatedRate   = calculateRate(wrapper.Rate);
                        int    calculatedVolume = calculateVolume(wrapper.Volume);

                        System.Diagnostics.Process speakToFileProcess = new System.Diagnostics.Process();

                        string outputFile = getOutputFile(wrapper.Uid);

                        string args = "--speakToFile" + " \"" +
                                      prepareText(wrapper) + "\" \"" +
                                      outputFile.Replace('"', '\'') + "\" " +
                                      calculatedRate.ToString() + " " +
                                      calculatedVolume.ToString() + " \"" +
                                      voiceName.Replace('"', '\'') + '"';

                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Process arguments: " + args);
                        }

                        speakToFileProcess.StartInfo.FileName  = application;
                        speakToFileProcess.StartInfo.Arguments = args;

                        System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakToFileProcess))
                        {
                            Name = wrapper.Uid.ToString()
                        };
                        worker.Start();

                        silence = false;
                        onSpeakAudioGenerationStart(wrapper);

                        do
                        {
                            System.Threading.Thread.Sleep(50);
                        } while (worker.IsAlive || !speakToFileProcess.HasExited);

                        if (speakToFileProcess.ExitCode == 0)
                        {
                            processAudioFile(wrapper, outputFile);
                        }
                        else
                        {
                            using (System.IO.StreamReader sr = speakToFileProcess.StandardError)
                            {
                                string errorMessage = "Could not generate the text: " + wrapper + System.Environment.NewLine + "Exit code: " + speakToFileProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                                Debug.LogError(errorMessage);
                                onErrorInfo(wrapper, errorMessage);
                            }
                        }

                        speakToFileProcess.Dispose();
                    }
                    else
                    {
                        string errorMessage = "Could not find the TTS-wrapper: '" + application + "'";
                        Debug.LogError(errorMessage);
                        onErrorInfo(wrapper, errorMessage);
                    }
                }
            }
        }
        public override IEnumerator SpeakNative(Model.Wrapper wrapper)
        {
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty!");
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    if (System.IO.File.Exists(applicationName))
                    {
                        string voiceName        = getVoiceName(wrapper);
                        int    calculatedRate   = calculateRate(wrapper.Rate);
                        int    calculatedVolume = calculateVolume(wrapper.Volume);

                        //string args = $"--speak -text \"{prepareText(wrapper)}\" -rate {calculatedRate} -volume {calculatedVolume} -voice \"{voiceName.Replace('"', '\'')}\"";
                        string args = "--speak " +
                                      "-text \"" + prepareText(wrapper) + "\" " +
                                      "-rate " + calculatedRate + " " +
                                      "-volume " + calculatedVolume + " " +
                                      "-voice \"" + voiceName.Replace('"', '\'') + '"';

                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Process arguments: " + args);
                        }
#if ENABLE_IL2CPP
                        Common.Util.CTProcess process = new Common.Util.CTProcess();
#else
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
#endif
                        //speakProcess.StartInfo.FileName = System.IO.Path.GetFileName(application);
                        //speakProcess.StartInfo.WorkingDirectory = System.IO.Path.GetDirectoryName(application);
                        process.StartInfo.FileName  = applicationName;
                        process.StartInfo.Arguments = args;

                        string[] speechTextArray = Util.Helper.CleanText(wrapper.Text, false)
                                                   .Split(splitCharWords, System.StringSplitOptions.RemoveEmptyEntries);
                        int    wordIndex        = 0;
                        int    wordIndexCompare = 0;
                        string phoneme          = string.Empty;
                        string viseme           = string.Empty;
                        bool   start            = false;
#if ENABLE_IL2CPP
                        System.Threading.Thread worker = new System.Threading.Thread(() => readSpeakNativeStream(ref process, ref speechTextArray, out wordIndex, out phoneme, out viseme, out start, useVisemesAndPhonemesIL2CPP, useVisemesAndPhonemesIL2CPP))
                        {
                            Name = wrapper.Uid
                        };
#else
                        System.Threading.Thread worker = new System.Threading.Thread(() =>
                                                                                     readSpeakNativeStream(ref process, ref speechTextArray, out wordIndex, out phoneme,
                                                                                                           out viseme, out start))
                        {
                            Name = wrapper.Uid
                        };
#endif
                        worker.Start();

                        silence = false;
#if ENABLE_IL2CPP
                        processCreators.Add(wrapper.Uid, process);
#else
                        processes.Add(wrapper.Uid, process);
#endif
                        do
                        {
                            yield return(null);

                            if (wordIndex != wordIndexCompare)
                            {
                                onSpeakCurrentWord(wrapper, speechTextArray, wordIndex - 1);

                                wordIndexCompare = wordIndex;
                            }

                            if (!string.IsNullOrEmpty(phoneme))
                            {
                                onSpeakCurrentPhoneme(wrapper, phoneme);

                                phoneme = string.Empty;
                            }

                            if (!string.IsNullOrEmpty(viseme))
                            {
                                onSpeakCurrentViseme(wrapper, viseme);

                                viseme = string.Empty;
                            }

                            if (start)
                            {
                                onSpeakStart(wrapper);

                                start = false;
                            }
                        } while (worker.IsAlive || !process.HasExited);

                        // clear output
                        onSpeakCurrentPhoneme(wrapper, string.Empty);
                        onSpeakCurrentViseme(wrapper, string.Empty);
#if ENABLE_IL2CPP
                        if (process.ExitCode == 0 || process.ExitCode == 123456) //123456 = Killed
#else
                        if (process.ExitCode == 0 || process.ExitCode == -1)     //-1 = Killed
#endif
                        {
                            if (Util.Config.DEBUG)
                            {
                                Debug.Log("Text spoken: " + wrapper.Text);
                            }

                            onSpeakComplete(wrapper);
                        }
                        else
                        {
                            using (System.IO.StreamReader sr = process.StandardError)
                            {
                                string errorMessage = "Could not speak the text: " + wrapper +
                                                      System.Environment.NewLine + "Exit code: " + process.ExitCode +
                                                      System.Environment.NewLine + sr.ReadToEnd();
                                Debug.LogError(errorMessage);
                                onErrorInfo(wrapper, errorMessage);
                            }
                        }
#if ENABLE_IL2CPP
                        processCreators.Remove(wrapper.Uid);
#else
                        processes.Remove(wrapper.Uid);
#endif
                        process.Dispose();
                    }
                    else
                    {
                        string errorMessage = "Could not find the TTS-wrapper: '" + applicationName + "'";
                        Debug.LogError(errorMessage);
                        onErrorInfo(wrapper, errorMessage);
                    }
                }
            }
        }
예제 #35
0
 public void Dispose()
 {
     _process.Dispose();
 }
예제 #36
0
 // Somebody asked for ping.kat.
 public void OnFileRequested(HttpRequest request, IDirectory directory)
 {
     request.Response.ResponseContent = new MemoryStream();
     StreamWriter textWriter = new StreamWriter(request.Response.ResponseContent);
     try
     {
         // Loop through each user and check if they're connected. If so,
         // increment the connected count.
         int usercount = 0;
         foreach (KeyValuePair<Guid,User> pair in users)
         {
             User user = pair.Value;
             if (user.Client != null && user.Client.Network.Connected)
             {
                 ++usercount;
             }
         }
         // Write out the connected count.
         textWriter.WriteLine(usercount);
         // Work out and write the time running in seconds.
         TimeSpan span = DateTime.UtcNow.Subtract(started);
         textWriter.WriteLine(span.TotalSeconds);
         try
         {
             // This is .NET-speak for "print exec('free')".
             // It's really rather complicated.
             // (N.B. "free" spits out how much memory you're using)
             System.Diagnostics.Process process = new System.Diagnostics.Process();
             process.StartInfo.UseShellExecute = false;
             process.StartInfo.RedirectStandardOutput = true;
             process.StartInfo.FileName = "free";
             process.Start();
             textWriter.Write(process.StandardOutput.ReadToEnd());
             process.WaitForExit();
             process.Dispose();
         }
         catch
         {
             textWriter.Write("Unable to get memory info.");
         }
     }
     catch (Exception exception)
     {
         this.contenttype = "text/plain";
         textWriter.WriteLine(exception.Message);
     }
     textWriter.Flush();
 }
        public override IEnumerator Generate(Model.Wrapper wrapper)
        {
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty: " + wrapper);
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    if (System.IO.File.Exists(applicationName))
                    {
                        string voiceName        = getVoiceName(wrapper);
                        int    calculatedRate   = calculateRate(wrapper.Rate);
                        int    calculatedVolume = calculateVolume(wrapper.Volume);

                        string outputFile = getOutputFile(wrapper.Uid);

                        string args = "--speakToFile " +
                                      "-text \"" + prepareText(wrapper) + "\" " +
                                      "-file \"" + outputFile.Replace('"', '\'') + "\" " +
                                      "-rate " + calculatedRate + " " +
                                      "-volume " + calculatedVolume + " " +
                                      "-voice \"" + voiceName.Replace('"', '\'') + '"';

                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Process arguments: " + args);
                        }
#if ENABLE_IL2CPP
                        Common.Util.CTProcess process = new Common.Util.CTProcess();
#else
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
#endif
                        process.StartInfo.FileName  = applicationName;
                        process.StartInfo.Arguments = args;

                        System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process, 0, false, false, false, false))
                        {
                            Name = wrapper.Uid
                        };
                        worker.Start();

                        silence = false;
                        onSpeakAudioGenerationStart(wrapper);

                        do
                        {
                            yield return(null);
                        } while (worker.IsAlive || !process.HasExited);

                        if (process.ExitCode == 0)
                        {
                            processAudioFile(wrapper, outputFile);
                        }
                        else
                        {
                            using (System.IO.StreamReader sr = process.StandardError)
                            {
                                string errorMessage = "Could not generate the text: " + wrapper +
                                                      System.Environment.NewLine + "Exit code: " + process.ExitCode +
                                                      System.Environment.NewLine + sr.ReadToEnd();
                                Debug.LogError(errorMessage);
                                onErrorInfo(wrapper, errorMessage);
                            }
                        }

                        process.Dispose();
                    }
                    else
                    {
                        string errorMessage = "Could not find the TTS-wrapper: '" + applicationName + "'";
                        Debug.LogError(errorMessage);
                        onErrorInfo(wrapper, errorMessage);
                    }
                }
            }
        }
예제 #38
0
 /// <summary>
 /// Handles a double-click of the tray icon
 /// </summary>
 /// <param name="sender">Object that sent doubleclick</param>
 /// <param name="e">Event arguments</param>
 private void OnNotifyIconDoubleClick(object sender, EventArgs e)
 {
     System.Diagnostics.Process taskMan = null;
     try
     {
         taskMan = new System.Diagnostics.Process();
         taskMan.StartInfo = new System.Diagnostics.ProcessStartInfo("taskmgr.exe");
         taskMan.Start();
     }
     catch (System.ComponentModel.Win32Exception ex)
     {
         System.Diagnostics.Trace.WriteLine("Could not start task manager: " + ex.Message);
     }
     finally
     {
         if (taskMan == null)
         {
             taskMan.Dispose();
         }
     }
 }
        private IEnumerator getVoices()
        {
            if (System.IO.File.Exists(applicationName))
            {
                System.Collections.Generic.List <Model.Voice>
                voices = new System.Collections.Generic.List <Model.Voice>();
#if ENABLE_IL2CPP
                Common.Util.CTProcess process = new Common.Util.CTProcess();
#else
                System.Diagnostics.Process process = new System.Diagnostics.Process();
#endif
                process.StartInfo.FileName  = applicationName;
                process.StartInfo.Arguments = "--voices";

                System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process, Util.Constants.DEFAULT_TTS_KILL_TIME));
                worker.Start();

                do
                {
                    yield return(null);
                } while (worker.IsAlive || !process.HasExited);

                if (process.ExitCode == 0)
                {
                    using (System.IO.StreamReader streamReader = process.StandardOutput)
                    {
                        while (!streamReader.EndOfStream)
                        {
                            var reply = streamReader.ReadLine();

                            if (Util.Config.DEBUG)
                            {
                                Debug.Log("reply: " + reply);
                            }

                            if (!string.IsNullOrEmpty(reply))
                            {
                                if (reply.StartsWith(idVoice))
                                {
                                    string[] splittedString = reply.Split(splitChar,
                                                                          System.StringSplitOptions.RemoveEmptyEntries);

                                    if (splittedString.Length == 6)
                                    {
                                        //if (!splittedString[1].CTContains("espeak")) //ignore eSpeak voices
                                        //{
                                        voices.Add(new Model.Voice(splittedString[1], splittedString[2],
                                                                   Util.Helper.StringToGender(splittedString[3]), splittedString[4],
                                                                   splittedString[5]));
                                        //}
                                    }
                                    else
                                    {
                                        Debug.LogWarning("Voice is invalid: " + reply);
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    using (System.IO.StreamReader sr = process.StandardError)
                    {
                        string errorMessage = "Could not get any voices: " + process.ExitCode +
                                              System.Environment.NewLine + sr.ReadToEnd();
                        Debug.LogError(errorMessage);
                        onErrorInfo(null, errorMessage);
                    }
                }

                process.Dispose();

                cachedVoices = voices.OrderBy(s => s.Name).ToList();

                if (Util.Constants.DEV_DEBUG)
                {
                    Debug.Log("Voices read: " + cachedVoices.CTDump());
                }
            }
            else
            {
                string errorMessage = "Could not find the TTS-wrapper: '" + applicationName + "'";
                Debug.LogError(errorMessage);
                onErrorInfo(null, errorMessage);
            }

            onVoicesReady();
        }
예제 #40
0
 private void textBoxDescription_LinkClicked(object sender, LinkClickedEventArgs e)
 {
     System.Diagnostics.Process p = new System.Diagnostics.Process();
     p.StartInfo.FileName = e.LinkText;
     p.Start();
     p.Dispose();
 }
예제 #41
0
 public static bool LogonMachines(string logonfile)
 {
     {
         string cmdname = "net";
         string cmdargs = "CONFIG SERVER /Autodisconnect:-1";
         System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(cmdname, cmdargs);
         psi.UseShellExecute       = false;
         psi.CreateNoWindow        = true;
         psi.RedirectStandardError = true;
         System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
         //proc.WaitForExit();
         string erroutput = proc.StandardError.ReadToEnd().Trim();
         proc.Dispose();
         if (erroutput.Length > 0)
         {
             throw new Exception("Process.Start(\"" + cmdname + "\", \"" + cmdargs + "\") error: " + erroutput);
         }
     }
     // File in the format:
     // <WindowsUser>
     // <machine>=<password>
     try
     {
         using (System.IO.StreamReader sr = new System.IO.StreamReader(logonfile))
         {
             string user = sr.ReadLine();
             if (string.IsNullOrEmpty(user))
             {
                 return(false);
             }
             for (; ;)
             {
                 string s = sr.ReadLine();
                 if (null == s)
                 {
                     break;
                 }
                 string machine = null;
                 string passwd  = s;
                 int    ieq     = s.IndexOf('=');
                 if (ieq > 0)
                 {
                     machine = s.Substring(0, ieq);
                     passwd  = s.Substring(ieq + 1);
                 }
                 else
                 {
                     //continue;
                     throw new InvalidOperationException("LogonMachines error in file (=)");
                 }
                 string netpath = NetworkPathForHost(machine);
                 int    idollar = netpath.IndexOf('$');
                 if (-1 == idollar)
                 {
                     //continue;
                     throw new InvalidOperationException("LogonMachines error in path ($)");
                 }
                 string sharepath = netpath.Substring(0, idollar + 1);
                 try
                 {
                     System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(sharepath);
                     // Note: ensuring di.Attributes call passes or fails.
                     if ((di.Attributes & System.IO.FileAttributes.Offline)
                         == System.IO.FileAttributes.Offline)
                     {
                         throw new System.IO.IOException("Network share is offline: " + sharepath);
                     }
                     // Has access...
                     continue;
                 }
                 catch
                 {
                 }
                 {
                     string cmdname = "net";
                     string cmdargs = "use * \"" + sharepath + "\" \"/USER:"******"\" + user + "\" \"" + passwd + "\"";
                     System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(cmdname, cmdargs);
                     psi.UseShellExecute       = false;
                     psi.CreateNoWindow        = true;
                     psi.RedirectStandardError = true;
                     System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
                     //proc.WaitForExit();
                     string erroutput = proc.StandardError.ReadToEnd().Trim();
                     proc.Dispose();
                     if (erroutput.Length > 0)
                     {
                         string safeargs = cmdargs;
                         {
                             const string findslashuser = "******";
                             int          islashuser    = cmdargs.IndexOf(findslashuser);
                             if (-1 != islashuser)
                             {
                                 safeargs = cmdargs.Substring(0, islashuser + findslashuser.Length) + "{masked}";
                             }
                         }
                         throw new Exception("Process.Start(\"" + cmdname + "\", \"" + safeargs + "\") error: " + erroutput);
                     }
                 }
             }
             return(true);
         }
     }
     catch (System.IO.FileNotFoundException)
     {
         return(false);
     }
 }
예제 #42
0
파일: frmMain.cs 프로젝트: Veivan/GanttDll
        void mnuNewInstance_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process instance = null;

            try
            {
                Program.CursorWait();
                instance = new System.Diagnostics.Process();
                instance.StartInfo.FileName = Application.ExecutablePath;
                instance.StartInfo.Arguments = "nosplash";
                instance.Start();
            }
            catch (Exception ex)
            {
                Program.CursorDefault();
                Program.ErrMsgBox(ex.Message);
            }
            finally
            {
                if (instance != null)
                    instance.Dispose();

                Program.CursorDefault();
            }
        }
예제 #43
0
 private void websiteLink_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e)
 {
     try
     {
         System.Diagnostics.Process start=new System.Diagnostics.Process();
         start.StartInfo.FileName="explorer.exe";
         start.StartInfo.Arguments="http://www.bluchip.co.in";
         start.Start();
         start.Dispose();
     }
     catch{}
 }
예제 #44
0
        public static PushEntity SendPushMsg(PushEntity PushEntity)
        {
            PushEntity.LogMessages.MsgType = MessageType.INFO;
            PushEntity.LogMessages.Content = _nameSpaceClass + "SendPushMsg";
            LoggerHelper.LogWriter(PushEntity.LogMessages);

            try
            {
                PushEntity.Result = 1;
                PushEntity.PushDBEntity[0].Status = "1";
                PushDBEntity dbParm = (PushEntity.PushDBEntity.Count > 0) ? PushEntity.PushDBEntity[0] : new PushDBEntity();
                PushEntity = PushDA.UpdateSendPushStatus(PushEntity);
                if (2 == PushEntity.Result)
                {
                    return PushEntity;
                }

                System.Diagnostics.Process process = new System.Diagnostics.Process();
                try
                {
                    process.StartInfo.FileName = ConfigurationManager.AppSettings["PushMsgJob"].ToString();//文件名必须加后缀。
                    process.StartInfo.Arguments = dbParm.ID;
                    process.Start();
                }
                catch (Exception exU)
                {
                    PushEntity.Result = 3;
                    PushEntity.PushDBEntity[0].Status = "0";
                    PushEntity = PushDA.UpdateSendPushStatus(PushEntity);
                }
                finally
                {
                    if (!process.HasExited)
                    {
                        process.Close();
                        process.Dispose();
                    }
                }
                return PushEntity;
            }
            catch (Exception ex)
            {
                PushEntity.LogMessages.MsgType = MessageType.ERROR;
                PushEntity.LogMessages.Content = _nameSpaceClass + "SendPushMsg  Error: " + ex.Message;
                LoggerHelper.LogWriter(PushEntity.LogMessages);
                throw ex;
            }
        }
예제 #45
0
        private void CreateProcess(string arguments)
        {
            // Create process
            var process = new System.Diagnostics.Process();
            process.StartInfo.FileName = "sqlcmd";
            process.StartInfo.Arguments = arguments;
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = false;
            process.Start();

            // Wait for process to finish
            process.WaitForExit();
            process.Close();
            process.Dispose();
        }
예제 #46
0
        private void procFawcl()
        {
            System.Collections.ObjectModel.ReadOnlyCollection<string> aacFiles =
                Microsoft.VisualBasic.FileIO.FileSystem.FindInFiles(
                this.TmpFolder,
                "ms",
                false,
                Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories,
                new string[] { "*.aac" });
            string aacFile = "";
            foreach (string af in aacFiles)
            {
                if (af.Contains(this.FileName)) aacFile = af;
            }

            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.Fawcl + " \"" + aacFile + "\"";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();

            System.Collections.ObjectModel.ReadOnlyCollection<string> wavFiles =
                Microsoft.VisualBasic.FileIO.FileSystem.FindInFiles(
                this.TmpFolder,
                "",
                false,
                Microsoft.VisualBasic.FileIO.SearchOption.SearchAllSubDirectories,
                new string[] { "*.wav" });
            string wavFile = "";
            foreach (string wf in wavFiles)
            {
                if (wf.Contains(this.FileName)) wavFile = wf;
            }

            System.Diagnostics.Process p2 = new System.Diagnostics.Process();

            p2.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p2.StartInfo.UseShellExecute = false;
            p2.StartInfo.CreateNoWindow = true;

            p2.StartInfo.Arguments = @"/c ";
            p2.StartInfo.Arguments += this.Fawcl + " \"" + wavFile + "\" ";
            p2.StartInfo.Arguments += "\"" + this.TmpFullPath + ".aac\"";

            System.Diagnostics.Process proc2 = System.Diagnostics.Process.Start(p2.StartInfo);
            proc2.WaitForExit();
            proc2.Dispose();
            p2.Dispose();

            this.addLogList("音声エンコード処理を完了");
        }
예제 #47
0
        public override IEnumerator SpeakNative(Model.Wrapper wrapper)
        {
#if UNITY_STANDALONE_WIN || UNITY_EDITOR
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty!");
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    string application = applicationName();

                    if (System.IO.File.Exists(application))
                    {
                        string voiceName        = getVoiceName(wrapper);
                        int    calculatedRate   = calculateRate(wrapper.Rate);
                        int    calculatedVolume = calculateVolume(wrapper.Volume);

                        System.Diagnostics.Process speakProcess = new System.Diagnostics.Process();

                        string args = "--speak " + '"' + prepareText(wrapper) + "\" " +
                                      calculatedRate.ToString() + " " +
                                      calculatedVolume.ToString() + " \"" +
                                      voiceName.Replace('"', '\'') + '"';

                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Process arguments: " + args);
                        }

                        speakProcess.StartInfo.FileName  = application;
                        speakProcess.StartInfo.Arguments = args;

                        string[] speechTextArray  = Util.Helper.CleanText(wrapper.Text, false).Split(splitCharWords, System.StringSplitOptions.RemoveEmptyEntries);
                        int      wordIndex        = 0;
                        int      wordIndexCompare = 0;
                        string   phoneme          = string.Empty;
                        string   viseme           = string.Empty;
                        bool     start            = false;

                        System.Threading.Thread worker = new System.Threading.Thread(() => readSpeakNativeStream(ref speakProcess, ref speechTextArray, out wordIndex, out phoneme, out viseme, out start))
                        {
                            Name = wrapper.Uid.ToString()
                        };
                        worker.Start();

                        silence = false;
                        processes.Add(wrapper.Uid, speakProcess);
                        //workers.Add(wrapper.Uid, worker);

                        do
                        {
                            yield return(null);

                            if (wordIndex != wordIndexCompare)
                            {
                                onSpeakCurrentWord(wrapper, speechTextArray, wordIndex - 1);

                                wordIndexCompare = wordIndex;
                            }

                            if (!string.IsNullOrEmpty(phoneme))
                            {
                                onSpeakCurrentPhoneme(wrapper, phoneme);

                                phoneme = string.Empty;
                            }

                            if (!string.IsNullOrEmpty(viseme))
                            {
                                onSpeakCurrentViseme(wrapper, viseme);

                                viseme = string.Empty;
                            }

                            if (start)
                            {
                                onSpeakStart(wrapper);

                                start = false;
                            }
                        } while (worker.IsAlive || !speakProcess.HasExited);

                        // clear output
                        onSpeakCurrentPhoneme(wrapper, string.Empty);
                        onSpeakCurrentViseme(wrapper, string.Empty);

                        if (speakProcess.ExitCode == 0 || speakProcess.ExitCode == -1)
                        { //0 = normal ended, -1 = killed
                            if (Util.Config.DEBUG)
                            {
                                Debug.Log("Text spoken: " + wrapper.Text);
                            }

                            onSpeakComplete(wrapper);
                        }
                        else
                        {
                            using (System.IO.StreamReader sr = speakProcess.StandardError)
                            {
                                string errorMessage = "Could not speak the text: " + wrapper + System.Environment.NewLine + "Exit code: " + speakProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                                Debug.LogError(errorMessage);
                                onErrorInfo(wrapper, errorMessage);
                            }
                        }

                        processes.Remove(wrapper.Uid);
                        //workers.Remove(wrapper.Uid);
                        speakProcess.Dispose();
                    }
                    else
                    {
                        string errorMessage = "Could not find the TTS-wrapper: '" + application + "'";
                        Debug.LogError(errorMessage);
                        onErrorInfo(wrapper, errorMessage);
                    }
                }
            }
#else
            yield return(null);
#endif
        }
예제 #48
0
        private void procTs2avs()
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.Ts2avs + " ";
            p.StartInfo.Arguments += "\"" + this.Avs + "\" ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".avs\" ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".demuxed.m2v\"";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();

            this.addLogList("ts2avs処理を完了");
        }
예제 #49
0
        private async Task <bool> ConvertMedia(string filePath, string aCodecId)
        {
            // codec id required for audio
            if (string.IsNullOrEmpty(aCodecId))
            {
                return(false);
            }

            // for now, only convert mkv
            if (System.IO.Path.GetExtension(filePath).ToLower() != ".mkv")
            {
                return(false);
            }

            // https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension
            var mpegFilePath = mFileInfo.Parent + "\\" + System.IO.Path.GetFileNameWithoutExtension(filePath)
                               + ".mp4";

            if (System.IO.File.Exists(mpegFilePath))
            {
                Console.WriteLine("mp4 file already exists!");
                mFileInfo.IsInError = true;
                return(false);
            }

            TaskCompletionSource <bool> ffmpegEventHandled = new TaskCompletionSource <bool>();

            using (System.Diagnostics.Process ffmpegProcess = new System.Diagnostics.Process {
                StartInfo =
                {
                    FileName        = FFMpegPath + @"\bin\ffmpeg.exe",
                    // ffmpeg remove menu chapters
                    // https://video.stackexchange.com/questions/20270/ffmpeg-delete-chapters
                    //  " -codec:s srt -map " + sCodecId
                    Arguments       = " -loglevel warning -i \"" + filePath + "\"" + " -sn -map_chapters -1 -codec:v" +
                                      " copy -map 0:v:0 -acodec copy -map " + aCodecId + " \"" + mpegFilePath + "\"",
                    UseShellExecute = false
                },
                EnableRaisingEvents = true
            }
                   ) {
                try {
                    // Start a process and raise an event when done.
                    ffmpegProcess.Exited += (sender, args) => {
                        if (ffmpegProcess.ExitCode != 0)
                        {
                            Console.WriteLine("Exit code: " + ffmpegProcess.ExitCode + ", ffmpeg is invoked " +
                                              "incorrectly! Please check input stream. args: " + ffmpegProcess.StartInfo.Arguments);
                            mFileInfo.Update("Fail: media conversion");
                            return;
                        }

                        Console.WriteLine("Elapsed time: " + Math.Round((ffmpegProcess.ExitTime - ffmpegProcess.
                                                                         StartTime).TotalMilliseconds) + " ms (change to mp4 container)");

                        ffmpegEventHandled.TrySetResult(true);
                        ffmpegProcess.Dispose();
                    };

                    ffmpegProcess.Start();
                }
                catch (Exception ex) {
                    Console.WriteLine($"An error occurred trying to run ffmpeg scodec copy \"{FFMpegPath}\"");
                    Console.WriteLine(ex.Message);
                    return(false);
                }

                long inSize = (new System.IO.FileInfo(filePath)).Length;

                // Wait for ffmpeg process Exited event, but not more than 40 seconds
                await Task.WhenAny(ffmpegEventHandled.Task, Task.Delay(40000));

                // after extracting if it results a small file < 50 MB of original
                long mpegSize = (new System.IO.FileInfo(mpegFilePath)).Length;

                if ((inSize - mpegSize) > (50 * 1024 * 1024))
                {
                    return(false);
                }
            }

            return(true);
        }
예제 #50
0
        private void procVideoMux()
        {
            System.Diagnostics.Process p = new System.Diagnostics.Process();

            p.StartInfo.FileName = System.Environment.GetEnvironmentVariable("ComSpec");
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.CreateNoWindow = true;

            p.StartInfo.Arguments = @"/c ";
            p.StartInfo.Arguments += this.Muxer + " -i ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".264\"";
            p.StartInfo.Arguments += " -o ";
            p.StartInfo.Arguments += "\"" + this.TmpFullPath + ".mp4\"";

            System.Diagnostics.Process proc = System.Diagnostics.Process.Start(p.StartInfo);
            proc.WaitForExit();
            proc.Dispose();
            p.Dispose();
        }
예제 #51
0
        void LoadFile(string filepath, bool isReloading)
        {
            // Convert file
            var filenameWE  = System.IO.Path.GetDirectoryName(filepath) + "/" + System.IO.Path.GetFileNameWithoutExtension(filepath);
            var ext         = System.IO.Path.GetExtension(filepath).ToLower().Replace(".", "");
            var newFilepath = filenameWE + ".efkmodel";

            Effekseer.Utl.ModelInformation modelInfo = new Utl.ModelInformation();
            if (modelInfo.Load(newFilepath))
            {
                if (!isReloading)
                {
                    binding.SetAbsolutePath(filepath);
                    System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
                    return;
                }
            }
            else
            {
                // Remove invalid file
                if (System.IO.File.Exists(newFilepath))
                {
                    try
                    {
                        System.IO.File.Delete(newFilepath);
                    }
                    catch
                    {
                    }
                }
            }

            Dialog.OpenModel omd = new Dialog.OpenModel(modelInfo.Scale);

            if (ext == "fbx" || ext == "mqo")
            {
                omd.Show("");
            }
            else
            {
                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);
            }

            omd.OnOK = () =>
            {
                if (ext == "fbx")
                {
                    var  oldFilepath = filepath;
                    bool doGenerate  = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/fbxToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }


                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.FileName  = converterPath;
                        info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                        p.WaitForExit();
                        p.Dispose();

                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                if (ext == "mqo")
                {
                    var oldFilepath = filepath;

                    bool doGenerate = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/mqoToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }

                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();
                        info.FileName  = converterPath;
                        info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);
                        p.WaitForExit();
                        p.Dispose();

                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);
            };
        }
        public override void SpeakNativeInEditor(Model.Wrapper wrapper)
        {
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'wrapper.Text' is null or empty!");
                }
                else
                {
                    if (System.IO.File.Exists(applicationName))
                    {
                        string voiceName        = getVoiceName(wrapper);
                        int    calculatedRate   = calculateRate(wrapper.Rate);
                        int    calculatedVolume = calculateVolume(wrapper.Volume);

                        string args = "--speak " +
                                      "-text \"" + prepareText(wrapper) + "\" " +
                                      "-rate " + calculatedRate + " " +
                                      "-volume " + calculatedVolume + " " +
                                      "-voice \"" + voiceName.Replace('"', '\'') + '"';

                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Process arguments: " + args);
                        }
#if ENABLE_IL2CPP
                        Common.Util.CTProcess process = new Common.Util.CTProcess();
#else
                        System.Diagnostics.Process process = new System.Diagnostics.Process();
#endif
                        process.StartInfo.FileName  = applicationName;
                        process.StartInfo.Arguments = args;

                        System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref process, 0, false, false, false, false))
                        {
                            Name = wrapper.Uid
                        };
                        worker.Start();

                        silence = false;
                        onSpeakStart(wrapper);

                        do
                        {
                            System.Threading.Thread.Sleep(50);

                            if (silence && !process.HasExited)
                            {
                                process.Kill();
                            }
                        } while (worker.IsAlive || !process.HasExited);
#if ENABLE_IL2CPP
                        if (process.ExitCode == 0 || process.ExitCode == 123456) //123456 = Killed
#else
                        if (process.ExitCode == 0 || process.ExitCode == -1)     //-1 = Killed
#endif
                        {
                            if (Util.Config.DEBUG)
                            {
                                Debug.Log("Text spoken: " + wrapper.Text);
                            }

                            onSpeakComplete(wrapper);
                        }
                        else
                        {
                            using (System.IO.StreamReader sr = process.StandardError)
                            {
                                Debug.LogError("Could not speak the text: " + process.ExitCode +
                                               System.Environment.NewLine + sr.ReadToEnd());
                            }
                        }

                        process.Dispose();
                    }
                    else
                    {
                        string errorMessage = "Could not find the TTS-wrapper: '" + applicationName + "'";
                        Debug.LogError(errorMessage);
                        onErrorInfo(wrapper, errorMessage);
                    }
                }
            }
        }
예제 #53
0
        public override IEnumerator SpeakNative(Model.Wrapper wrapper)
        {
#if (UNITY_STANDALONE_OSX || UNITY_EDITOR) && !UNITY_WEBPLAYER
            if (wrapper == null)
            {
                Debug.LogWarning("'wrapper' is null!");
            }
            else
            {
                if (string.IsNullOrEmpty(wrapper.Text))
                {
                    Debug.LogWarning("'Text' is null or empty: " + wrapper);
                    //yield return null;
                }
                else
                {
                    yield return(null); //return to the main process (uid)

                    string speaker        = string.Empty;
                    int    calculatedRate = calculateRate(wrapper.Rate);

                    if (wrapper.Voice == null || string.IsNullOrEmpty(wrapper.Voice.Name))
                    {
                        if (Util.Config.DEBUG)
                        {
                            Debug.LogWarning("'Voice' or 'Voice.Name' is null! Using the OS 'default' voice.");
                        }
                    }
                    else
                    {
                        speaker = wrapper.Voice.Name;
                    }

                    //using (System.Diagnostics.Process speakProcess = new System.Diagnostics.Process())
                    //{

                    System.Diagnostics.Process speakProcess = new System.Diagnostics.Process();

                    string args = (string.IsNullOrEmpty(speaker) ? string.Empty : (" -v \"" + speaker.Replace('"', '\'') + '"')) +
                                  (calculatedRate != defaultRate ? (" -r " + calculatedRate) : string.Empty) + " \"" +
                                  wrapper.Text.Replace('"', '\'') + '"';

                    if (Util.Config.DEBUG)
                    {
                        Debug.Log("Process argruments: " + args);
                    }

                    speakProcess.StartInfo.FileName       = Util.Config.TTS_MACOS;
                    speakProcess.StartInfo.Arguments      = args;
                    speakProcess.StartInfo.CreateNoWindow = true;
                    //speakProcess.StartInfo.RedirectStandardOutput = true;
                    speakProcess.StartInfo.RedirectStandardError = true;
                    speakProcess.StartInfo.UseShellExecute       = false;
                    //speakProcess.StartInfo.StandardOutputEncoding = System.Text.Encoding.UTF8;
                    //* Set your output and error (asynchronous) handlers
                    //speakProcess.OutputDataReceived += new DataReceivedEventHandler(speakNativeHandler);
                    //scanProcess.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler);

                    //speakProcess.Start();
                    //speakProcess.BeginOutputReadLine();
                    //speakProcess.BeginErrorReadLine();

                    System.Threading.Thread worker = new System.Threading.Thread(() => startProcess(ref speakProcess))
                    {
                        Name = wrapper.Uid.ToString()
                    };
                    worker.Start();

                    silence = false;

                    processes.Add(wrapper.Uid, speakProcess);
                    onSpeakStart(wrapper);

                    do
                    {
                        yield return(null);
                    } while (worker.IsAlive || !speakProcess.HasExited);

                    if (speakProcess.ExitCode == 0 || speakProcess.ExitCode == -1)
                    { //0 = normal ended, -1 = killed
                        if (Util.Config.DEBUG)
                        {
                            Debug.Log("Text spoken: " + wrapper.Text);
                        }
                    }
                    else
                    {
                        using (System.IO.StreamReader sr = speakProcess.StandardError)
                        {
                            string errorMessage = "Could not speak the text: " + speakProcess.ExitCode + System.Environment.NewLine + sr.ReadToEnd();
                            Debug.LogError(errorMessage);
                            onErrorInfo(wrapper, errorMessage);
                        }
                    }

                    processes.Remove(wrapper.Uid);
                    onSpeakComplete(wrapper);

                    speakProcess.Dispose();
                    //}
                }
            }
#else
            yield return(null);
#endif
        }
예제 #54
0
        void LoadFile(string filepath, bool isReloading)
        {
            // Convert file
            var ext         = System.IO.Path.GetExtension(filepath).ToLower().Replace(".", "");
            var newFilepath = System.IO.Path.ChangeExtension(filepath, ".efkmodel");

            Effekseer.Utl.ModelInformation modelInfo = new Utl.ModelInformation();
            if (modelInfo.Load(newFilepath))
            {
                if (!isReloading)
                {
                    binding.SetAbsolutePath(filepath);
                    System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));
                    return;
                }
            }
            else
            {
                // Remove invalid file
                if (System.IO.File.Exists(newFilepath))
                {
                    try
                    {
                        System.IO.File.Delete(newFilepath);
                    }
                    catch
                    {
                    }
                }
            }

            Dialog.OpenModel omd = new Dialog.OpenModel(modelInfo.Scale);

            if (ext == "fbx" || ext == "mqo")
            {
                omd.Show("");
            }
            else
            {
                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);
            }

            omd.OnOK = () =>
            {
                if (ext == "fbx")
                {
                    var  oldFilepath = filepath;
                    bool doGenerate  = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/fbxToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }


                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

                        var os = System.Environment.OSVersion;
                        if (os.Platform == PlatformID.Win32NT ||
                            os.Platform == PlatformID.Win32S ||
                            os.Platform == PlatformID.Win32Windows ||
                            os.Platform == PlatformID.WinCE)
                        {
                            converterPath += ".exe";
                        }

                        if (os.Platform == PlatformID.Unix && os.Platform != PlatformID.MacOSX)
                        {
                            string pathvar = System.Environment.GetEnvironmentVariable("LD_LIBRARY_PATH");
                            info.EnvironmentVariables["LD_LIBRARY_PATH"] = pathvar + ";" + Manager.GetEntryDirectory() + "/tools/";
                        }

                        info.FileName = converterPath;

                        info.Arguments = "\"" + oldFilepath + "\" \"" + newFilepath + "\" -scale " + omd.Magnification.ToString();

                        if (!System.IO.File.Exists(oldFilepath))
                        {
                            var msg = oldFilepath + " is not found.";

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                            return;
                        }

                        if (!System.IO.File.Exists(converterPath))
                        {
                            var msg = converterPath + " is not found.";

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                            return;
                        }

                        info.UseShellExecute        = false;
                        info.RedirectStandardOutput = true;
                        info.RedirectStandardInput  = false;
                        info.CreateNoWindow         = true;

                        System.Diagnostics.Process p = System.Diagnostics.Process.Start(info);

                        string outputs = p.StandardOutput.ReadToEnd();

                        p.WaitForExit();
                        p.Dispose();


                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }
                        else
                        {
                            var msg = " Failed to load. \n" + outputs;

                            swig.GUIManager.show(msg, "Error", swig.DialogStyle.Error, swig.DialogButtons.OK);
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                if (ext == "mqo")
                {
                    var oldFilepath = filepath;

                    bool doGenerate = false;

                    if (!System.IO.File.Exists(newFilepath) ||
                        System.IO.File.GetLastWriteTime(oldFilepath) != System.IO.File.GetLastWriteTime(newFilepath) ||
                        modelInfo.Scale != omd.Magnification)
                    {
                        doGenerate = true;
                    }

                    if (doGenerate)
                    {
                        string converterPath = Manager.GetEntryDirectory() + "/tools/mqoToEffekseerModelConverter";

                        // japanese file path is not supported.
                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Copy(oldFilepath, tempFilePath);
                            oldFilepath = tempFilePath;
                        }
                        catch
                        {
                        }

                        System.Diagnostics.ProcessStartInfo info = new System.Diagnostics.ProcessStartInfo();

                        var os = System.Environment.OSVersion;
                        if (os.Platform == PlatformID.Win32NT ||
                            os.Platform == PlatformID.Win32S ||
                            os.Platform == PlatformID.Win32Windows ||
                            os.Platform == PlatformID.WinCE)
                        {
                            converterPath += ".exe";
                        }

                        try
                        {
                            mqoToEffekseerModelConverter.Program.Call(new[] { oldFilepath, newFilepath, "-scale", omd.Magnification.ToString() });
                        }
                        catch
                        {
                        }

                        if (System.IO.File.Exists(newFilepath))
                        {
                            System.IO.File.SetLastWriteTime(newFilepath, System.IO.File.GetLastWriteTime(oldFilepath));
                        }

                        try
                        {
                            string tempFilePath = Path.GetTempPath() + System.IO.Path.GetFileName(filepath);
                            System.IO.File.Delete(tempFilePath);
                        }
                        catch
                        {
                        }
                    }
                }

                binding.SetAbsolutePath(filepath);

                System.IO.Directory.SetCurrentDirectory(System.IO.Path.GetDirectoryName(filepath));

                Manager.Viewer.Reload(true);

                Read();
            };
        }
예제 #55
0
        private void BuildConfig(
            string projectName,
            string projectFolder,
            System.Guid projectGuid,
            string output,
            string outputFolder,
            Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Settings settings,
            Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Config config,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Reference> references,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.ProjectReference> projectReferences,
            List <Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Item> items,
            ProjectBuildTracker projectBuildTracker)
        {
            this._output.Add(new Output("Begin Build " + projectName));
            this._output.Add(new Output(""));



            System.IO.DirectoryInfo directoryInfo = new System.IO.FileInfo(output).Directory;
            if (!directoryInfo.Exists)
            {
                directoryInfo.Create();
            }



            Bamboo.CSharp.Compilers.CompilerParameters compilerParameters = new Bamboo.CSharp.Compilers.CompilerParameters();

            if (settings.ApplicationIcon.Length > 0)
            {
                compilerParameters.ApplicationIcon = projectFolder + System.IO.Path.DirectorySeparatorChar + settings.ApplicationIcon;
            }

            compilerParameters.Assembly = output;

            compilerParameters.Target = settings.OutputType.ToLower();

            compilerParameters.Define = config.DefineConstants;
            if (config.DebugSymbols.Length == 0)
            {
                compilerParameters.Debug = false;
            }
            else
            {
                compilerParameters.Debug = System.Boolean.Parse(config.DebugSymbols);
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Reference reference in references)
            {
                if (ProjectReferenceRules.IsFrameworkReference(reference))
                {
                    //
                    // Framework reference.
                    //
                    string frameworkPath = this._compiler.GetFrameworkPath();
                    string referencePath = frameworkPath + reference.Include + ".dll";

                    if (!System.IO.File.Exists(referencePath))
                    {
                    }
                    else
                    {
                        compilerParameters.References.Add(referencePath);
                    }
                }
                else if (ProjectReferenceRules.IsAssemblyFolderReference(reference))
                {
                    //
                    // AssemblyFolder reference.
                    //
                    string referencePath = ProjectReferenceRules.GetReferencePath(projectFolder, reference.HintPath, this._compiler);
                    if (referencePath != null)
                    {
                        if (System.IO.File.Exists(referencePath))
                        {
                            compilerParameters.References.Add(referencePath);
                        }
                        else if (System.IO.File.Exists(referencePath + ".dll"))
                        {
                            compilerParameters.References.Add(referencePath + ".dll");
                        }
                        else
                        {
                        }
                    }
                }
                else
                {
                    //
                    // File reference.
                    //
                    string referencePath = ProjectReferenceRules.GetReferencePath(projectFolder, reference.HintPath, this._compiler);
                    if (referencePath != null)
                    {
                        string output_folder = new System.IO.FileInfo(output).DirectoryName;
                        if (!output_folder.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                        {
                            output_folder += System.IO.Path.DirectorySeparatorChar;
                        }
                        string target = output_folder + new System.IO.FileInfo(referencePath).Name;
                        if (!target.Equals(referencePath))
                        {
                            System.IO.File.Copy(referencePath, target, true);

                            while (!System.IO.File.Exists(target))
                            {
                                System.Threading.Thread.Sleep(500);
                            }
                        }

                        compilerParameters.References.Add(referencePath);
                    }
                }
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.ProjectReference projectReference in projectReferences)
            {
                //
                // Project reference.
                //
                string projectReferencePath = projectBuildTracker.GetPath(new System.Guid(projectReference.Project));

                if (projectReferencePath != null)
                {
                    string output_folder = new System.IO.FileInfo(output).DirectoryName;
                    if (!output_folder.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()))
                    {
                        output_folder += System.IO.Path.DirectorySeparatorChar;
                    }
                    string target = output_folder + new System.IO.FileInfo(projectReferencePath).Name;
                    if (!target.Equals(projectReferencePath))
                    {
                        System.IO.File.Copy(projectReferencePath, target, true);

                        while (!System.IO.File.Exists(target))
                        {
                            System.Threading.Thread.Sleep(500);
                        }
                    }
                    compilerParameters.References.Add(target);
                }
            }
            foreach (Bamboo.VisualStudio.VisualStudio2008.CSharpProject.Models.Item item in items)
            {
                if (item.Type == "Compile")
                {
                    compilerParameters.Sources.Add(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include);
                }
                else if (item.Type == "Content")
                {
                    System.IO.FileInfo fileInfo = new System.IO.FileInfo(outputFolder + item.Include);
                    if (!fileInfo.Directory.Exists)
                    {
                        fileInfo.Directory.Create();
                    }
                    System.IO.File.Copy(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include, outputFolder + item.Include, true);
                }
                else if (item.Type == "None" && item.Include.Equals("App.config"))
                {
                    System.IO.File.Copy(projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include, output + ".config");
                }
                else if (item.Type == "EmbeddedResource")
                {
                    if (item.Include.ToLower().EndsWith(".resx"))
                    {
                        string RESGEN_EXE = Bamboo.CSharp.FrameworkDetector.GetSDKInstallRoot("v" + this._compiler.GetFrameworkVersion()) + "Bin\\resgen.exe";
                        //TODO OLD string RESGEN_EXE = @"C:\Program Files\Swampware\SDK\NET_2.0\resgen.exe";

                        System.Diagnostics.ProcessStartInfo processStartInfo = new System.Diagnostics.ProcessStartInfo();
                        processStartInfo.FileName = RESGEN_EXE;
                        processStartInfo.RedirectStandardOutput = true;
                        processStartInfo.UseShellExecute        = false;
                        processStartInfo.CreateNoWindow         = true;
                        processStartInfo.WorkingDirectory       = System.Environment.CurrentDirectory;

                        string arguments = "\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include + "\"";

                        string resourceFile  = item.Include.Substring(0, item.Include.Length - 5) + ".resources";
                        string resource_name = settings.RootNamespace + "." + resourceFile.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), ".");
                        string resource_path = "\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res" + System.IO.Path.DirectorySeparatorChar + resource_name + "\"";
                        arguments += " " + resource_path;

                        if (!System.IO.Directory.Exists(projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res"))
                        {
                            System.IO.Directory.CreateDirectory(projectFolder + System.IO.Path.DirectorySeparatorChar + "obj" + System.IO.Path.DirectorySeparatorChar + "res");
                        }

                        processStartInfo.Arguments = arguments;
                        System.Diagnostics.Process process = System.Diagnostics.Process.Start(processStartInfo);

                        System.IO.StringWriter stringWriter = new System.IO.StringWriter();
                        while (!process.HasExited)
                        {
                            stringWriter.Write(process.StandardOutput.ReadToEnd());
                            process.WaitForExit(50);
                        }
                        stringWriter.Write(process.StandardOutput.ReadToEnd());
                        process.Close();
                        process.Dispose();

                        this._output.Add(new Output(stringWriter.ToString()));



                        this._output.Add(new Output("Converting " + item.Include + " to " + resourceFile + ""));

                        compilerParameters.Resources.Add(resource_path);
                    }
                    else
                    {
                        string resource_name = settings.RootNamespace + "." + item.Include.Replace(System.IO.Path.DirectorySeparatorChar.ToString(), ".");

                        compilerParameters.Resources.Add("\"" + projectFolder + System.IO.Path.DirectorySeparatorChar + item.Include + "\"" + "," + resource_name);
                    }
                }
            }


            this._compiler.Compile(compilerParameters);



            //
            // Output
            //
            foreach (string line in compilerParameters.Output)
            {
                this._output.Add(new Output(line));
            }

            //
            // Errors
            //
            bool hasErrors = false;

            foreach (Bamboo.CSharp.Compilers.Error error in compilerParameters.Errors)
            {
                if (!error.IsWarning)
                {
                    hasErrors = true;
                }
                this._errors.Add(new Error(error.IsWarning, error.File, error.Line, error.Column, error.Code, error.Description, error.Text));
            }



            if (hasErrors)
            {
                this._succeeded = false;
                this._output.Add(new Output(""));
                this._output.Add(new Output("Build Failed " + projectName));
            }
            else
            {
                this._succeeded = true;
                this._assembly  = compilerParameters.Assembly;
                this._output.Add(new Output(""));
                this._output.Add(new Output("Build Succeeded " + projectName));

                projectBuildTracker.Add(projectGuid, compilerParameters.Assembly);
            }
        }
예제 #56
0
파일: Graphics.cs 프로젝트: poppa/MediaDB
        /// <summary>
        /// Execute ImageMagicks "convert".
        /// </summary>
        /// <param name="args">
        /// A <see cref="System.String"/>
        /// </param>
        /// <param name="outfile">
        /// A <see cref="System.String"/>
        /// </param>
        /// <returns>
        /// A <see cref="System.Byte"/> array
        /// </returns>
        private static byte[] iMagickConvert(string args, string outfile)
        {
            // TODO: Resolve the relative exe issue for Windows
            System.Diagnostics.Process proc;
            proc = new System.Diagnostics.Process();
            proc.EnableRaisingEvents = false;
            #if LINUX
            proc.StartInfo.FileName = "convert";
            #else
            proc.StartInfo.FileName = @"C:\Program Files\ImageMagick-6.6.3-Q16\convert.exe";
            //proc.StartInfo.FileName = "\"convert.exe\"";
            #endif
            proc.StartInfo.Arguments = args;
            proc.StartInfo.UseShellExecute = false;
            proc.StartInfo.RedirectStandardError = true;
            proc.Start();

            string error = proc.StandardError.ReadToEnd();

            if (!proc.HasExited)
                proc.WaitForExit();

            if (proc.ExitCode == 0) {
                var fi = new FileInfo(outfile);
                var fs = new FileStream(outfile, FileMode.Open, FileAccess.Read);
                byte[] buf = new byte[fi.Length];
                fs.Read(buf, 0, buf.Length);
                fs.Close();
                fs.Dispose();
                fi.Delete();
                fi = null;

                proc.Close();
                proc.Dispose();
                proc = null;

                return buf;
            }
            else {
                if (!error.Contains("no 8BIM data is available"))
                    Log.Warning("Unable to \"convert\": {0}\n### {1}\n", args, error);
            }

            proc.Close();
            proc.Dispose();
            proc = null;

            return null;
        }
예제 #57
0
        private async Task ExtractSubtitle(string filePath, string sCodecId)
        {
            // mkv, mp4, mpeg-2 m2ts, mov, qt can contain subtitles as attachments
            // ref, https://en.wikipedia.org/wiki/Comparison_of_video_container_formats
            // for now, for psa and rmz we only accept mkv
            if (System.IO.Path.GetExtension(filePath).ToLower() != ".mkv")
            {
                return;
            }

            // https://docs.microsoft.com/en-us/dotnet/api/system.io.path.getfilenamewithoutextension
            var subRipExt   = ".srt";
            var srtFilePath = mFileInfo.Parent + "\\" + System.IO.Path.GetFileNameWithoutExtension(filePath)
                              + subRipExt;

            if (System.IO.File.Exists(srtFilePath))
            {
                Console.WriteLine("Subrip file already exists, renaming");
                var oldSrtFilePath = srtFilePath.Substring(0, srtFilePath.Length - subRipExt.Length) + "_old.srt";

                if (System.IO.File.Exists(oldSrtFilePath))
                {
                    FileOperationAPIWrapper.Send(oldSrtFilePath);
                }

                System.IO.File.Move(srtFilePath, oldSrtFilePath);
            }

            TaskCompletionSource <bool> ffmpegEventHandled = new TaskCompletionSource <bool>();

            using (System.Diagnostics.Process ffmpegProcess = new System.Diagnostics.Process {
                StartInfo =
                {
                    FileName        = FFMpegPath + @"\bin\ffmpeg.exe",
                    // -y overwrite output file if exists
                    Arguments       = " -loglevel warning -i \"" + filePath + "\"" + " -codec:s srt -map " +
                                      sCodecId + " \"" + srtFilePath + "\"",
                    UseShellExecute = false
                },
                EnableRaisingEvents = true
            }
                   ) {
                try {
                    // Start a process and raise an event when done.
                    ffmpegProcess.Exited += (sender, args) => {
                        if (ffmpegProcess.ExitCode != 0)
                        {
                            Console.WriteLine("Exit code: " + ffmpegProcess.ExitCode + ", an overwrite is not " +
                                              "confirmed or ffmpeg is invoked incorrectly! Please check input stream. codec id: " + sCodecId);
                        }

                        Console.Write("Subtitle extraction time: " + Math.Round((ffmpegProcess.ExitTime - ffmpegProcess.
                                                                                 StartTime).TotalMilliseconds) + " ms (), ");

                        ffmpegEventHandled.TrySetResult(true);
                        ffmpegProcess.Dispose();
                    };

                    ffmpegProcess.Start();
                    // better to utilize onExit than `WaitForExit`
                }
                catch (Exception ex) {
                    Console.WriteLine($"An error occurred trying to run ffmpeg scodec copy \"{FFMpegPath}\"");
                    Console.WriteLine(ex.Message);
                    return;
                }

                // Run Concurrent
                // Cleanup garbage sub
                // Change sponsor text in psarip subs

                // Wait for ffmpeg process Exited event, but not more than 120 seconds
                await Task.WhenAny(ffmpegEventHandled.Task, Task.Delay(120000));
            }

            // after extracting if it results a garbage subtitle (with sCount > 1) set shouldChangeContainer to false
            long srtSize = (new System.IO.FileInfo(srtFilePath)).Length;

            Console.WriteLine("Srt size: {0:F2} KB", srtSize * 1.0 / 1024);

            // Expecting at least 5 KB; if found less notify, but don't affect cont. change
            if (srtSize < (5 * 1024))
            {
                Console.WriteLine("Subtitle file size is small (< 5 KB)!");
                // ShouldChangeContainer = false;
            }
        }
        public bool MirrorFileGeodatabases(string SourceFileGeodatabasePathName, string DestinationFileGeodatabasePathName, string RobocopyExecutablePath, string MirrorOperationCommandLineParams)
        {
            System.Diagnostics.Process fileGeoDBMirrorProcess = null;

              try
              {
            //  Let the User know what is happening.
            if (ProcessMessage != null)
            {
              ProcessMessage("            > Initializing the File Geodatabase Mirroring Operation...");
              ProcessMessage("               < Verifying that the Source and Destination File Geodatabases Exist...");
            }

            //  Confirm that the Source File Geodatabase exists.
            if (!System.IO.Directory.Exists(SourceFileGeodatabasePathName))
            {
              //  Let the user know that the Source File Geodatabase does not exist.
              if (ErrorMessage != null)
              {
            ErrorMessage("The Source File Geodatabase - " + SourceFileGeodatabasePathName + " - does not exist.  Aborting the MaintTools.FeatureClassUtilities.MirrorFileGeodatabases() Method!");
              }

              //  Return FALSE to the calling method to indicate that this method failed.
              return false;

            }

            //  Confirm that the Destination File Geodatabase exists.
            if (!System.IO.Directory.Exists(DestinationFileGeodatabasePathName))
            {
              //  Let the user know that the Destination File Geodatabase does not exist.
              if (ErrorMessage != null)
              {
            ErrorMessage("The Destination File Geodatabase - " + DestinationFileGeodatabasePathName + " - does not exist.  Aborting the MaintTools.FeatureClassUtilities.MirrorFileGeodatabases() Method!");
              }

              //  Return FALSE to the calling method to indicate that this method failed.
              return false;

            }

            //  Let the User know what is happening.
            if (ProcessMessage != null)
            {
              ProcessMessage("               < Confirming the Robocopy Executable Path for this Server...");
            }

            //  Confirm that the Robocopy Executable Path is valid.
            if (!System.IO.File.Exists(RobocopyExecutablePath))
            {
              //  Let the user know that the Robocopy Executable Path is not valid
              if (ErrorMessage != null)
              {
            ErrorMessage("The Robocopy Executable Path - " + RobocopyExecutablePath + " - is not valid.  Aborting the MaintTools.FeatureClassUtilities.MirrorFileGeodatabases() Method!");
              }

              //  Return FALSE to the calling method to indicate that this method failed.
              return false;

            }

            //  Determine the Command Line switches that will be used for the Mirror Operation.
            string finalCommandLineSwitches = null;
            if (System.String.IsNullOrEmpty(MirrorOperationCommandLineParams))
            {
              //  Let the user know that the default command Line switches will be used.
              if (ProcessMessage != null)
              {
            ProcessMessage("               < No command line switches were passed to this method.  The following default switches will be used -");
            ProcessMessage("                  - /MIR /XF *.lock /R:5 /W:2 /NP /TEE");
              }

              //  Set the command line switches that will be used.
              finalCommandLineSwitches = "/MIR /XF *.lock /R:5 /W:2 /NP /TEE";

            }
            else
            {
              //  Let the user know that the passed command Line switches will be used.
              if (ProcessMessage != null)
              {
            ProcessMessage("               < The passed command line switches -" + MirrorOperationCommandLineParams + " - will be used for this mirror operation.");
              }

              //  Set the command line switches that will be used.
              finalCommandLineSwitches = MirrorOperationCommandLineParams;

            }

            //  Let the User know what is happening.
            if (ProcessMessage != null)
            {
              ProcessMessage("            > Beginning the mirror of the " + SourceFileGeodatabasePathName + " File Geodatabase to the " + DestinationFileGeodatabasePathName + " File Geodatabase...");
              ProcessMessage("               < Buiilding the Process to complete the mirror operation and starting the update...");
            }

            //  Build the System process to Update the File Geodatabase.
            fileGeoDBMirrorProcess = new System.Diagnostics.Process();
            fileGeoDBMirrorProcess.EnableRaisingEvents = false;
            fileGeoDBMirrorProcess.StartInfo.Arguments = SourceFileGeodatabasePathName + " " + DestinationFileGeodatabasePathName + " " + finalCommandLineSwitches;
            fileGeoDBMirrorProcess.StartInfo.FileName = RobocopyExecutablePath;
            fileGeoDBMirrorProcess.Start();
            fileGeoDBMirrorProcess.WaitForExit();

            //  Wait for the process to exit.
            while (!fileGeoDBMirrorProcess.HasExited)
            {
              //  Pause for 10 seconds to wait for the process to exit.
              System.Threading.Thread.Sleep(10000);
            }

            //  Let the User know that the Mirror Operation has finished.
            if (ProcessMessage != null)
            {
              ProcessMessage("               < The process to mirror the File Geodatabases has finished.  The exit code from the process was - " + fileGeoDBMirrorProcess.ExitCode.ToString() + "...");
            }

            //  Determine if the copy Operation finished successfully.
            if ((fileGeoDBMirrorProcess.ExitCode != 0) && (fileGeoDBMirrorProcess.ExitCode != 1) && (fileGeoDBMirrorProcess.ExitCode != 3) && (fileGeoDBMirrorProcess.ExitCode != 2))
            {
              //  Let the User know that the File Geodatabase mirror operation failed.
              if (ErrorMessage != null)
              {
            ErrorMessage("The Mirror of the " + SourceFileGeodatabasePathName + " File Geodatabase to the " + DestinationFileGeodatabasePathName + " File Geodatabase failed.  Aborting the MaintTools.FeatureClassUtilities.MirrorFileGeodatabases() Method!");
              }

              //  Return FALSE to the calling method to indicate that this process failed.
              return false;

            }
            else
            {
              //  Let the User know that the Mirror Operation finished successfully.
              if (ProcessMessage != null)
              {
            ProcessMessage("               < Successfully mirrored the File Geodatabases...");
              }

              //  Return TRUE to the calling method to indicate that the mirror operation finished successfully.
              return true;

            }

              }
              catch (System.Exception caught)
              {
            //  Determine the Line Number from which the exception was thrown.
            System.Diagnostics.StackTrace stackTrace = new System.Diagnostics.StackTrace(caught, true);
            System.Diagnostics.StackFrame stackFrame = stackTrace.GetFrame(stackTrace.FrameCount - 1);
            int lineNumber = stackFrame.GetFileLineNumber();

            //  Let the User know that this process failed.
            if (ErrorMessage != null)
            {
              ErrorMessage("The MaintTools.FeatureClassUtilities.MirrorFileGeodatabases() Method failed with error message:  " + caught.Message + " (Line:  " + lineNumber.ToString() + ")!");
            }

            //  Return FALSE to the calling routine to indicate that this process failed.
            return false;

              }
              finally
              {
            //  If the System Process Object was instantiated, close it.
            if (fileGeoDBMirrorProcess != null)
            {
              fileGeoDBMirrorProcess.Dispose();
              fileGeoDBMirrorProcess = null;
            }

              }
        }
예제 #59
0
        public void BtOverlayVideo_Click(object sender, EventArgs e)
        {
            //該当フェーズ部分をオーバーレイして表示する

            //System.Diagnostics.Process p = new System.Diagnostics.Process();

            //とりあえずパスを通した
            string directoryName1 = "K:\\CAM\\Aside\\!forC#\\" + laShootNum1.Text + ".MP4";
            string directoryName2 = "K:\\CAM\\Aside\\!forC#\\" + laShootNum2.Text + ".MP4";

            double assocTimeAStart = -1;
            double assocTimeAEnd   = -1;
            double assocTimeBStart = -1;
            double assocTimeBEnd   = -1;

            //2つの射の重ね合わせ動画は、対応するAssocTabTimeで合わせる
            StreamReader sr1 = new StreamReader("assoctab_3_" + laShootNum1.Text + ".csv");
            int          assocTimeALength = (File.ReadAllLines("assoctab_3_" + laShootNum1.Text + ".csv")).Length;

            int lineACount = 0;

            while (!sr1.EndOfStream)
            {
                string   line   = sr1.ReadLine();  //CSVの1行読み込み
                string[] values = line.Split(','); //カンマに分け配列に格納
                //はじめの時刻を取りに行く
                lineACount++;

                if (lineACount == 2)
                {
                    assocTimeAEnd = Double.Parse(values[5]);
                }
                else if (lineACount == assocTimeALength)
                {
                    assocTimeAStart = Double.Parse(values[5]);
                }
            }

            StreamReader sr2 = new StreamReader("assoctab_3_" + laShootNum2.Text + ".csv");
            int          assocTimeBLength = (File.ReadAllLines("assoctab_3_" + laShootNum2.Text + ".csv")).Length;
            int          lineBCount       = 0;

            while (!sr2.EndOfStream)
            {
                string   line   = sr2.ReadLine();  //CSVの1行読み込み
                string[] values = line.Split(','); //カンマに分け配列に格納
                lineBCount++;
                //はじめの時刻を取りに行く
                if (lineBCount == 2)
                {
                    assocTimeBEnd = Double.Parse(values[5]);
                }
                else if (lineBCount == assocTimeBLength)
                {
                    assocTimeBStart = Double.Parse(values[5]);
                }
            }


            //再生時間が300fpsなら5倍になっている /300*60 をする

            if (assocTimeAStart > 0 && assocTimeAEnd > 0 && assocTimeBStart > 0 && assocTimeBEnd > 0)
            {
                string video1starttime = (assocTimeAStart * ViewShootingVideo.playtimes).ToString();
                string video1cutLength = ((assocTimeAEnd - assocTimeAStart) * ViewShootingVideo.playtimes).ToString();
                string video2strattime = (assocTimeBStart * ViewShootingVideo.playtimes).ToString();
                string video2cutLength = ((assocTimeBEnd - assocTimeBStart) * ViewShootingVideo.playtimes).ToString();

                //p.StartInfo.FileName = "ffmpeg";

                //-y :強制上書きオプション
                // [ " を書く必要があるため \" で ” を表しています]
                // -ss:切り出しはじめの時刻 -t:切り出す範囲の時刻 -i:入力
                //blend filter takes two input streams and outputs one stream, the first input is the "top" layer and second input is "bottom" layer
                //overlayフィルタだけでは透過にならず、blendを使う必要がある
                //[0:0]1つ目の動画   [1:0]2つ目の動画
                //blend=all_mode=difference : 差分を表示 blend=c0_mode=average:普通に重畳

                string[] paras0 =
                {
                    //ffmpeg.exeのある場所
                    //出力ファイルもこちらにされる
                    " cd C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug"
                };

                //string[] paras = { "-y -ss", video1starttime, " -t", video1cutLength, " -i" ,directoryName1, " -ss",
                //     video2strattime, " -t", video2cutLength, "-i", directoryName2 ,
                //    "-filter_complex \"[0:0]split[shoot1][shoot2]; [shoot1] [1:0] overlay[overlay]; [overlay] [shoot2] blend=all_mode=difference \" -map 1:1 overlay"+ laShootNum1.Text + "_" + laShootNum2.Text  +".MP4"
                //    };

                //string[] paras = { "ffmpeg -y -i " + directoryName1 +  " -filter_complex  \"[0:v]colorchannelmixer=0:0:0:0.9:1:0:0:0.9:1:0:0:0.9[colorchannelmixed];[colorchannelmixed]eq=1:0.3:1:1:1:1:1:1[color_effect]\" -map [color_effect] -c:v libx264 -c:a copy output_video1.MP4"
                //      + " && ffmpeg -y -i " + directoryName2 + " -filter_complex \"[0:v]colorchannelmixer=1:0:0:0:0:0:0:0:0:0:0:0[colorchannelmixed];[colorchannelmixed]eq=1:1:1:1:1:1:1:1[color_effect]\" -map [color_effect] -c:v libx264 -c:a copy output_video2.MP4"
                //         + " && ffmpeg -y -i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video1.MP4 - i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video2.MP4 - filter_complex \"blend=all_opacity=0.7\" " + laShootNum1.Text + "_" + laShootNum2.Text + ".MP4"
                //};
                // "/C ffmpeg

                //https://nico-lab.net/edgedetect_with_ffmpeg/

                string[] paras1 = { "-y -ss " + video1starttime + " -t " + video1cutLength + " -i " + directoryName1 + " -filter_complex \"[0:v] edgedetect=10/255:50/255:wires[edge],[edge]colorchannelmixer=0:0:0:0.9:1:0:0:0.9:1:0:0:0.9[colorchannelmixed];[colorchannelmixed]eq=1:0.3:1:1:1:1:1:1[color_effect]\" -map [color_effect] -c:v libx264 -c:a copy output_video" + laShootNum1.Text + ".MP4" };

                //add" -ignore_chapter 1" if you have output trable
                string[] paras2 = { "-y -ss " + video2strattime + " -t " + video2cutLength + " -i " + directoryName2 + " -filter_complex \"[0:v] edgedetect=10/255:50/255:wires[edge],[edge]colorchannelmixer=1:0:0:0.9:0:0:0:0.9:0:0:0:0.9[colorchannelmixed];[colorchannelmixed]eq=1:0.3:1:1:1:1:1:1[color_effect]\" -map [color_effect] -c:v libx264 -c:a copy output_video" + laShootNum2.Text + ".MP4" };

                string[] paras3 =
                {
                    "-y -i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video" + laShootNum2.Text + ".MP4 -i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video" + laShootNum1.Text + ".MP4 -filter_complex \"blend=all_opacity=0.7\" " + "blue" + laShootNum1.Text + "_" + "red" + laShootNum2.Text + ".MP4"
                    //"-i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video" + laShootNum2.Text +".MP4 -i C:\\Users\\MIDORI\\Source\\Repos\\DTWandKmeansClastering\\DTWandKmeansClastering\\bin\\Debug\\output_video"+ laShootNum1.Text +".MP4 -filter_complex \"[0:0]split[shoot1][shoot2]; [shoot1] [1:0] overlay[overlay]; [overlay] [shoot2] blend=all_mode=difference \" -map 1:1 overlay"+ laShootNum1.Text + "_" + laShootNum2.Text  +".MP4"
                };


                //https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.synchronizingobject?view=netframework-4.8#System_Diagnostics_Process_SynchronizingObject
                //for (int cn = 1; cn < 2; cn++)
                //{
#if false
                System.Diagnostics.Process p = new System.Diagnostics.Process();
                //string para = "paras" + cn;
                p.StartInfo.FileName = "cmd.exe";
                //cmd// p.StartInfo.FileName = "cmd.exe";
                ;   //cmd// p.StartInfo.FileName = "cmd.exe";
                    //Console.WriteLine(string.Join(" ", paras1));
                    //p.StartInfo.StandardOutputEncoding = Encoding.UTF8;
                    //cmd//p.StartInfo.Arguments = string.Join(" ", paras1);
                    //cmd//p.StartInfo.Arguments = string.Join(p.StartInfo.Arguments, paras2);
                    //cmd//p.StartInfo.Arguments = string.Join(p.StartInfo.Arguments, paras3);
                p.StartInfo.Arguments              = string.Join("  /K", paras1);
                p.StartInfo.UseShellExecute        = false;     //don't use the operating system shell
                p.StartInfo.RedirectStandardOutput = true;      //put output directly in Process.StandardOutput
                p.StartInfo.RedirectStandardInput  = true;      //put input directly in Process.StandardOutput
                p.StartInfo.CreateNoWindow         = true;      //don't make new Window


                try
                {
                    p.Start();
                    //p.Exited += new EventHandler(MyProcessExited);
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
#else
#endif
                //batファイルと文字列の組み合わせで実行できなかったため、中身を文字列にして実行することに
                System.Diagnostics.Process p = System.Diagnostics.Process.Start("cmd.exe", paras0[0]);
                //System.Diagnostics.Process p = System.Diagnostics.Process.Start("ff.bat");
                //p.WaitForExit();

                //    p.Dispose();
                //}

                System.Diagnostics.Process p2 = new System.Diagnostics.Process();
                p2.StartInfo.FileName               = "ffmpeg";
                p2.StartInfo.Arguments              = string.Join("", paras1[0]);
                p2.StartInfo.UseShellExecute        = false; //don't use the operating system shell
                p2.StartInfo.RedirectStandardOutput = true;  //put output directly in Process.StandardOutput
                p2.StartInfo.RedirectStandardInput  = true;  //put input directly in Process.StandardOutput
                p2.StartInfo.CreateNoWindow         = true;  //don't make new Window


                try
                {
                    p2.Start();
                    p2.WaitForExit();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
                p2.Dispose();


                System.Diagnostics.Process p3 = new System.Diagnostics.Process();
                p3.StartInfo.FileName               = "ffmpeg";
                p3.StartInfo.Arguments              = string.Join("", paras2[0]);
                p3.StartInfo.UseShellExecute        = false; //don't use the operating system shell
                p3.StartInfo.RedirectStandardOutput = true;  //put output directly in Process.StandardOutput
                p3.StartInfo.RedirectStandardInput  = true;  //put input directly in Process.StandardOutput
                p3.StartInfo.CreateNoWindow         = true;  //don't make new Window


                try
                {
                    p3.Start();
                    p3.WaitForExit();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
                p3.Dispose();

                System.Diagnostics.Process p4 = new System.Diagnostics.Process();
                p4.StartInfo.FileName               = "ffmpeg";
                p4.StartInfo.Arguments              = string.Join("", paras3[0]);
                p4.StartInfo.UseShellExecute        = false; //don't use the operating system shell
                p4.StartInfo.RedirectStandardOutput = true;  //put output directly in Process.StandardOutput
                p4.StartInfo.RedirectStandardInput  = true;  //put input directly in Process.StandardOutput
                p4.StartInfo.CreateNoWindow         = true;  //don't make new Window


                try
                {
                    p4.Start();
                    p4.WaitForExit();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception.Message);
                }
                p4.Dispose();

                //cmd上での動作が終るまでプロセスpは閉じない
                //p.WaitForExit();
                p.Dispose();

                ShowOverlayVideo(int.Parse(laShootNum1.Text), int.Parse(laShootNum2.Text));

                MessageBox.Show("Output video finished");
            }
            else
            {
                MessageBox.Show("assocTime Read Error");
            }
        }