Exemplo n.º 1
0
        private void IPCAddTalkTask03(string TalkText, int iSpeed, int iTone, int iVolume, int vType)
        {
            int        cid;
            List <int> CidList  = Config.AvatorNames.Select(c => c.Key).ToList();
            int        cnt      = CidList.Count;
            int        ListenIf = (int)ListenInterface.IPC1;
            int        voice    = EditInputText.EditInputString((vType > 8 || vType == -1 ? 0 : vType), TalkText);

            cid = UserData.SelectedCid[ListenIf][voice];
            switch (UserData.RandomVoiceMethod[ListenIf])
            {
            case 1:
                voice = r.Next(0, 9);
                cid   = UserData.SelectedCid[ListenIf][voice];
                break;

            case 2:
                cid = CidList[r.Next(0, cnt)];
                if (Config.AvatorNames.ContainsKey(cid))
                {
                    UserData.VoiceParams[ListenIf][voice][cid] = Config.AvatorParams(cid);
                }
                break;
            }

            Dictionary <string, decimal> Effects  = UserData.VoiceParams[ListenIf][voice][cid]["effect"].ToDictionary(k => k.Key, v => v.Value["value"]);
            Dictionary <string, decimal> Emotions = UserData.VoiceParams[ListenIf][voice][cid]["emotion"].ToDictionary(k => k.Key, v => v.Value["value"]);

            MessageData talk = new MessageData()
            {
                Cid             = cid,
                Message         = EditInputText.ChangedTalkText,
                BouyomiVoice    = voice,
                ListenInterface = ListenIf,
                TaskId          = MessQue.count + 1,
                Effects         = Effects,
                Emotions        = Emotions
            };

            switch (PlayMethod)
            {
            case Methods.sync:
                MessQue.AddQueue(talk);
                break;

            case Methods.async:
                OnCallAsyncTalk?.Invoke(talk);
                break;
            }
        }
Exemplo n.º 2
0
        private Action SetupBGHttpListenerTask()
        {
            Action BGHttpListen = (() => {
                StringBuilder sb = new StringBuilder();
                string listFmt = @"""id"":{0}, ""kind"":""AquesTalk"", ""name"":""{1}"", ""alias"":""""";

                List <int> CidList = Config.AvatorNames.Select(c => c.Key).ToList();
                int cnt = CidList.Count;
                int cid;
                int ListenIf;

                while (KeepListen) // とりあえずの待ち受け構造
                {
                    try
                    {
                        HttpListenerContext context = HTTPListener.GetContext();
                        HttpListenerRequest request = context.Request;
                        HttpListenerResponse response = context.Response;
                        int voice = 0;
                        string TalkText = "本日は晴天ですか?";
                        string UrlPath = request.Url.AbsolutePath.ToUpper();

                        foreach (var item in Regex.Split(request.Url.Query, @"[&?]"))
                        {
                            if (item == "")
                            {
                                continue;
                            }

                            string[] s = Regex.Split(item, "=");
                            if (s.Length < 2)
                            {
                                s = new string[] { HttpUtility.UrlDecode(s[0]), "" }
                            }
                            ;
                            if (s.Length >= 2)
                            {
                                s = new string[] { HttpUtility.UrlDecode(s[0]), HttpUtility.UrlDecode(s[1]) }
                            }
                            ;

                            switch (s[0])
                            {
                            case "text":
                                TalkText = s[1];
                                break;

                            case "voice":
                                int.TryParse(s[1], out voice);
                                break;

                            case "volume":
                            case "speed":
                            case "tone":
                            default:
                                break;
                            }
                        }

                        response.ContentType = "application/json; charset=utf-8";

                        if (ListenPort == Config.HttpPortNum2)
                        {
                            ListenIf = (int)ListenInterface.Http2;
                        }
                        else
                        {
                            ListenIf = (int)ListenInterface.Http1;
                        }

                        voice = EditInputText.EditInputString((voice > 8 || voice == -1 ? 0 : voice), TalkText);
                        cid = UserData.SelectedCid[ListenIf][voice];
                        switch (UserData.RandomVoiceMethod[ListenIf])
                        {
                        case 1:
                            voice = r.Next(0, 9);
                            cid = UserData.SelectedCid[ListenIf][voice];
                            break;

                        case 2:
                            cid = CidList[r.Next(0, cnt)];
                            if (Config.AvatorNames.ContainsKey(cid))
                            {
                                UserData.VoiceParams[ListenIf][voice][cid] = Config.AvatorParams(cid);
                            }
                            break;
                        }

                        // dispath url
                        switch (UrlPath)
                        {
                        case "/TALK":
                            Dictionary <string, decimal> Effects = UserData.VoiceParams[ListenIf][voice][cid]["effect"].ToDictionary(k => k.Key, v => v.Value["value"]);
                            Dictionary <string, decimal> Emotions = UserData.VoiceParams[ListenIf][voice][cid]["emotion"].ToDictionary(k => k.Key, v => v.Value["value"]);

                            MessageData talk = new MessageData()
                            {
                                Cid = cid,
                                Message = EditInputText.ChangedTalkText,
                                BouyomiVoice = voice,
                                ListenInterface = ListenIf,
                                TaskId = MessQue.count + 1,
                                Effects = Effects,
                                Emotions = Emotions
                            };

                            switch (PlayMethod)
                            {
                            case Methods.sync:
                                MessQue.AddQueue(talk);
                                break;

                            case Methods.async:
                                OnCallAsyncTalk?.Invoke(talk);
                                break;
                            }

                            byte[] responseTalkContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""taskId"":{0}", talk.TaskId) + "}");
                            response.OutputStream.Write(responseTalkContent, 0, responseTalkContent.Length);
                            response.Close();
                            break;

                        case "/GETVOICELIST":
                            sb.Clear();
                            sb.AppendLine(@"{ ""voiceList"":[");
                            sb.Append(
                                string.Join(",", Config.AvatorNames.Select(v => string.Format(listFmt, v.Key, v.Value))
                                            .Select(v => "{" + v + "}")
                                            .ToArray())
                                );
                            sb.AppendLine(@"] }");

                            byte[] responseListContent = Encoding.UTF8.GetBytes(sb.ToString());
                            response.OutputStream.Write(responseListContent, 0, responseListContent.Length);
                            response.Close();
                            break;

                        case "/GETTALKTASKCOUNT":
                            byte[] responseTaskCountContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""talkTaskCount"":{0}", MessQue.count) + "}");
                            response.OutputStream.Write(responseTaskCountContent, 0, responseTaskCountContent.Length);
                            response.Close();
                            break;

                        case "/GETNOWTASKID":
                            byte[] responseTaskNowContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""nowTaskId"":{0}", taskId) + "}");
                            response.OutputStream.Write(responseTaskNowContent, 0, responseTaskNowContent.Length);
                            response.Close();
                            break;

                        case "/GETNOWPLAYING":
                            byte[] responseTaskPlayingContent = Encoding.UTF8.GetBytes("{" + string.Format(@"""nowPlaying"":{0}", MessQue.count != 0) + "}");
                            response.OutputStream.Write(responseTaskPlayingContent, 0, responseTaskPlayingContent.Length);
                            response.Close();
                            break;

                        case "/CLEAR":
                            byte[] responseTaskClearContent = Encoding.UTF8.GetBytes(@"{}");
                            response.OutputStream.Write(responseTaskClearContent, 0, responseTaskClearContent.Length);
                            response.Close();
                            break;

                        default:
                            byte[] responseMessageContent = Encoding.UTF8.GetBytes(@"{ ""Message"":""content not found.""}");
                            response.StatusCode = 404;
                            response.OutputStream.Write(responseMessageContent, 0, responseMessageContent.Length);
                            response.Close();
                            break;
                        }
                    }
                    catch (Exception)
                    {
                        //Dispatcher.Invoke(() =>
                        //{
                        //    MessageBox.Show(e.Message, "sorry3");
                        //});
                    }
                }
            });

            return(BGHttpListen);
        }
Exemplo n.º 3
0
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            Title = titleStr + " " + versionStr;

            try
            {
                // AssistantSeikaとの接続
                // シンプルな例は
                // https://hgotoh.jp/wiki/doku.php/documents/voiceroid/assistantseika/interface/wcf/wcf-004
                // を見てください。
                WcfClient = new WCFClient();

                if (WcfClient.AvatorList().Count == 0)
                {
                    throw new Exception("No Avators detected from AssistantSeika");
                }

                // 設定色々
                Config = new Configs(ref WcfClient);
            }
            catch (Exception e0)
            {
                MessageBox.Show("前提ソフトウエアであるAssistantSeikaを起動していないか、AssistantSeikaが音声合成製品を認識していない可能性があります。" + "\n" + e0.Message, "AssistantSeikaの状態");
                Application.Current.Shutdown();
                return;
            }

            try
            {
                // 古いバージョンの設定値のバージョンアップを試みる
                if (Properties.Settings.Default.UpgradeRequired)
                {
                    Properties.Settings.Default.Upgrade();
                    Properties.Settings.Default.UpgradeRequired = false;
                    //Properties.Settings.Default.Save();
                }
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message, "設定値読み込みの問題1");
                Application.Current.Shutdown();
                return;
            }

            try
            {
                // 設定値を取り込むよ!
                UserData = new UserDefData();
                if (Properties.Settings.Default.UserSettings != "")
                {
                    DataContractJsonSerializer uds = new DataContractJsonSerializer(typeof(UserDefData));
                    MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Properties.Settings.Default.UserSettings));
                    UserData = (UserDefData)uds.ReadObject(ms);
                    ms.Close();
                }
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message, "設定値読み込みの問題2");
                Application.Current.Shutdown();
                return;
            }

            try
            {
                // 設定値を取り込むよ!
                UserData.QuietMessages = Config.MessageLoader();
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message, "設定値読み込みの問題3");
                Application.Current.Shutdown();
                return;
            }

            try
            {
                // 古い版のデータだったら補正
                // 設定値が取り込めない環境がある模様だ。対策する

                if (UserData is null)
                {
                    UserData = new UserDefData();
                }

                if (UserData.VoiceParams is null)
                {
                    UserData.VoiceParams        = new Dictionary <int, Dictionary <int, Dictionary <int, Dictionary <string, Dictionary <string, Dictionary <string, decimal> > > > > >();
                    UserData.SelectedCid        = new Dictionary <int, Dictionary <int, int> >();
                    UserData.SelectedCallMethod = new Dictionary <int, int>();

                    foreach (ListenInterface InterfaceIdx in Enum.GetValues(typeof(ListenInterface)))
                    {
                        UserData.VoiceParams[(int)InterfaceIdx]        = new Dictionary <int, Dictionary <int, Dictionary <string, Dictionary <string, Dictionary <string, decimal> > > > >();
                        UserData.SelectedCid[(int)InterfaceIdx]        = new Dictionary <int, int>();
                        UserData.SelectedCallMethod[(int)InterfaceIdx] = (int)Methods.sync;

                        foreach (BouyomiVoice BouIdx in Enum.GetValues(typeof(BouyomiVoice)))
                        {
                            UserData.VoiceParams[(int)InterfaceIdx][(int)BouIdx] = new Dictionary <int, Dictionary <string, Dictionary <string, Dictionary <string, decimal> > > >();
                            UserData.SelectedCid[(int)InterfaceIdx][(int)BouIdx] = Config.AvatorNames.First().Key;

                            foreach (int cid in Config.AvatorNames.Keys)
                            {
                                UserData.VoiceParams[(int)InterfaceIdx][(int)BouIdx][cid] = Config.AvatorParams(cid);
                            }
                        }
                    }
                }

                if (UserData.InterfaceSwitch is null)
                {
                    UserData.InterfaceSwitch = new Dictionary <int, bool>()
                    {
                        { 0, true },
                        { 1, true },
                        { 2, true },
                        { 3, false },
                        { 4, false }
                    };
                }

                if (UserData.RandomVoiceMethod is null)
                {
                    UserData.RandomVoiceMethod = new Dictionary <int, int>()
                    {
                        { 0, 0 },
                        { 1, 0 },
                        { 2, 0 },
                        { 3, 0 },
                        { 4, 0 }
                    };
                }

                if (UserData.QuietMessages is null)
                {
                    UserData.QuietMessages = new Dictionary <int, List <string> >();
                }

                if (UserData.AddSuffixStr is null)
                {
                    UserData.AddSuffix    = false;
                    UserData.AddSuffixStr = "(以下略";
                    UserData.TextLength   = 96;
                }

                if (UserData.ReplaceDefs is null)
                {
                    UserData.ReplaceDefs = new List <ReplaceDefinition>();
                    UserData.ReplaceDefs.Add(new ReplaceDefinition()
                    {
                        Apply = true, MatchingPattern = @"([^0-90-9])[88]{3,}", ReplaceText = @"$1パチパチパチ"
                    });
                    UserData.ReplaceDefs.Add(new ReplaceDefinition()
                    {
                        Apply = true, MatchingPattern = @"^[88]{3,}", ReplaceText = @"パチパチパチ"
                    });
                    UserData.ReplaceDefs.Add(new ReplaceDefinition()
                    {
                        Apply = true, MatchingPattern = @"([^a-zA-Za-zA-Z])[WwWw]{1,}", ReplaceText = @"$1わらわら"
                    });
                    UserData.ReplaceDefs.Add(new ReplaceDefinition()
                    {
                        Apply = true, MatchingPattern = @"^[WwWw]{2,}", ReplaceText = @"わらわら"
                    });
                    UserData.ReplaceDefs.Add(new ReplaceDefinition()
                    {
                        Apply = true, MatchingPattern = @"https*:\/\/[^\t  ]{1,}", ReplaceText = @"URL省略"
                    });
                }
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message, "設定値読み込みの問題4");
                Application.Current.Shutdown();
                return;
            }

            try
            {
                // 以前より話者が増えていた場合、その話者の音声パラメタを初期化

                foreach (ListenInterface InterfaceIdx in Enum.GetValues(typeof(ListenInterface)))
                {
                    foreach (BouyomiVoice BouIdx in Enum.GetValues(typeof(BouyomiVoice)))
                    {
                        foreach (int cid in Config.AvatorNames.Keys)
                        {
                            if (!UserData.VoiceParams[(int)InterfaceIdx][(int)BouIdx].ContainsKey(cid))
                            {
                                UserData.VoiceParams[(int)InterfaceIdx][(int)BouIdx][cid] = Config.AvatorParams(cid);
                            }
                        }
                    }
                }
            }
            catch (Exception e0)
            {
                MessageBox.Show(e0.Message, "設定値読み込みの問題5");
                Application.Current.Shutdown();
                return;
            }

            // サイレントメッセージ最大待ち時間
            if (UserData.QuietMessages.Count != 0)
            {
                QuietMessageKeyMax = UserData.QuietMessages.Max(c => c.Key);
                if (QuietMessageKeyMax > (2 * 24 * 60 * 60))
                {
                    QuietMessageKeyMax     = 2 * 24 * 60 * 60; // 2日間
                    UserData.QuietMessages = UserData.QuietMessages.Where(c => c.Key <= QuietMessageKeyMax).ToDictionary(c => c.Key, v => v.Value);
                }

                CheckBoxIsSilent.IsChecked = UserData.IsSilentAvator;
            }
            else
            {
                QuietMessageKeyMax         = 0;
                CheckBoxIsSilent.IsChecked = false;
                CheckBoxIsSilent.IsEnabled = false;
            }

            // バックグラウンドタスク用オブジェクト
            IpcTask   = new IpcTasks(ref Config, ref MessQueWrapper, ref WcfClient, ref UserData);
            SockTask  = new SocketTasks(ref Config, ref MessQueWrapper, ref WcfClient, ref UserData);
            SockTask2 = new SocketTasks(ref Config, ref MessQueWrapper, ref WcfClient, ref UserData);
            HttpTask  = new HttpTasks(ref Config, ref MessQueWrapper, ref WcfClient, ref UserData);
            HttpTask2 = new HttpTasks(ref Config, ref MessQueWrapper, ref WcfClient, ref UserData);

            // 非同期発声時のGUI操作用
            IpcTask.OnCallAsyncTalk   += TalkAsyncCall;
            SockTask.OnCallAsyncTalk  += TalkAsyncCall;
            SockTask2.OnCallAsyncTalk += TalkAsyncCall;
            HttpTask.OnCallAsyncTalk  += TalkAsyncCall;
            HttpTask2.OnCallAsyncTalk += TalkAsyncCall;

            // 話者設定 コンボボックス設定
            ComboBoxInterface.ItemsSource       = null;
            ComboBoxInterface.ItemsSource       = ConstClass.BouyomiInterface;
            ComboBoxInterface.DisplayMemberPath = "LabelData";
            ComboBoxInterface.SelectedValuePath = "ValueData";

            ComboBoxCallMethod.ItemsSource       = null;
            ComboBoxCallMethod.ItemsSource       = ConstClass.BouyomiCallMethod;
            ComboBoxCallMethod.DisplayMemberPath = "LabelData";
            ComboBoxCallMethod.SelectedValuePath = "ValueData";

            List <ComboBox> MapAvatorsComboBoxList = new List <ComboBox>()
            {
                ComboBoxMapVoice0,
                ComboBoxMapVoice1,
                ComboBoxMapVoice2,
                ComboBoxMapVoice3,
                ComboBoxMapVoice4,
                ComboBoxMapVoice5,
                ComboBoxMapVoice6,
                ComboBoxMapVoice7,
                ComboBoxMapVoice8
            };

            for (int idx = 0; idx < MapAvatorsComboBoxList.Count; idx++)
            {
                MapAvatorsComboBoxList[idx].ItemsSource = null;
                MapAvatorsComboBoxList[idx].ItemsSource = Config.AvatorNames;
                MapAvatorsComboBoxList[idx].IsEnabled   = true;
                MapAvatorsComboBoxList[idx].Tag         = idx;
            }

            ComboBoxRandomAssignVoice.ItemsSource   = null;
            ComboBoxRandomAssignVoice.ItemsSource   = ConstClass.RandomAssignMethod;
            ComboBoxRandomAssignVoice.SelectedIndex = UserData.RandomVoiceMethod[(int)ListenInterface.IPC1];

            ComboBoxInterface.SelectedIndex = (int)ListenInterface.IPC1;

            // 音声設定 コンボボックス設定
            ComboBoxEditInterface.ItemsSource       = null;
            ComboBoxEditInterface.DisplayMemberPath = "LabelData";
            ComboBoxEditInterface.SelectedValuePath = "ValueData";
            ComboBoxEditInterface.ItemsSource       = ConstClass.BouyomiInterface;

            ComboBoxEditBouyomiVoice.ItemsSource       = null;
            ComboBoxEditBouyomiVoice.DisplayMemberPath = "LabelData";
            ComboBoxEditBouyomiVoice.SelectedValuePath = "ValueData";
            ComboBoxEditBouyomiVoice.ItemsSource       = ConstClass.BouyomiVoiceName;

            ComboBoxEditInterface.SelectedIndex    = 0;
            ComboBoxEditBouyomiVoice.SelectedIndex = 0;

            // 置換設定 テキストボックス設定
            TextBoxTextLength.Text           = UserData.TextLength.ToString();
            EditParamsBefore.LimitTextLength = UserData.TextLength;
            CheckBoxAddSuffix.IsChecked      = EditParamsBefore.IsUseSuffixString = UserData.AddSuffix;
            TextBoxAddSuffixStr.Text         = EditParamsBefore.SuffixString = UserData.AddSuffixStr;
            Regexs = new ObservableCollection <ReplaceDefinition>(UserData.ReplaceDefs);
            DataGridRepDefs.DataContext = null;
            DataGridRepDefs.DataContext = Regexs;
            if (UserData.ReplaceDefs.Count != 0)
            {
                DataGridRepDefs.SelectedIndex = 0;
            }
            EditParamsBefore.CopyRegExs(ref Regexs);

            // 状態 受信インタフェース
            EllipseIpc.Tag     = 0;
            EllipseSocket.Tag  = 1;
            EllipseHTTP.Tag    = 2;
            EllipseSocket2.Tag = 3;
            EllipseHTTP2.Tag   = 4;

            try
            {
                // 読み上げバックグラウンドタスク起動
                LonelyAvatorNames   = Config.AvatorNames;
                LonelyCidList       = LonelyAvatorNames.Select(c => c.Key).ToList();
                LonelyCount         = 0;
                KickTalker          = new DispatcherTimer();
                KickTalker.Tick    += new EventHandler(KickTalker_Tick);
                KickTalker.Interval = new TimeSpan(0, 0, 1);
                ReEntry             = true;
                KickTalker.Start();

                // 受信インタフェース バックグラウンドタスク起動

                if ((UserData.InterfaceSwitch[(int)ListenInterface.IPC1] == true) && IpcTask.StartIpcTasks(Config.IPCChannelName))
                {
                    EllipseIpc.Fill = Brushes.LightGreen;
                    UserData.InterfaceSwitch[(int)ListenInterface.IPC1] = true;
                }
                else
                {
                    EllipseIpc.Fill = Brushes.Black;
                    UserData.InterfaceSwitch[(int)ListenInterface.IPC1] = false;
                }

                if (UserData.InterfaceSwitch[(int)ListenInterface.Socket1] == true)
                {
                    SockTask.StartSocketTasks(Config.SocketAddress, Config.SocketPortNum);
                    EllipseSocket.Fill = Brushes.LightGreen;
                    UserData.InterfaceSwitch[(int)ListenInterface.Socket1] = true;
                }
                else
                {
                    EllipseSocket.Fill = Brushes.Black;
                    UserData.InterfaceSwitch[(int)ListenInterface.Socket1] = false;
                }

                if (UserData.InterfaceSwitch[(int)ListenInterface.Http1] == true)
                {
                    HttpTask.StartHttpTasks(Config.HttpAddress, Config.HttpPortNum);
                    EllipseHTTP.Fill = Brushes.LightGreen;
                    UserData.InterfaceSwitch[(int)ListenInterface.Http1] = true;
                }
                else
                {
                    EllipseHTTP.Fill = Brushes.Black;
                    UserData.InterfaceSwitch[(int)ListenInterface.Http1] = false;
                }

                if (UserData.InterfaceSwitch[(int)ListenInterface.Socket2] == true)
                {
                    SockTask2.StartSocketTasks(Config.SocketAddress2, Config.SocketPortNum2);
                    EllipseSocket2.Fill = Brushes.LightGreen;
                    UserData.InterfaceSwitch[(int)ListenInterface.Socket2] = true;
                }
                else
                {
                    EllipseSocket2.Fill = Brushes.Black;
                    UserData.InterfaceSwitch[(int)ListenInterface.Socket2] = false;
                }

                if (UserData.InterfaceSwitch[(int)ListenInterface.Http2] == true)
                {
                    HttpTask2.StartHttpTasks(Config.HttpAddress2, Config.HttpPortNum2);
                    EllipseHTTP2.Fill = Brushes.LightGreen;
                    UserData.InterfaceSwitch[(int)ListenInterface.Http2] = true;
                }
                else
                {
                    EllipseHTTP2.Fill = Brushes.Black;
                    UserData.InterfaceSwitch[(int)ListenInterface.Http2] = false;
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, titleStr + " 1");
                Application.Current.Shutdown();
            }
        }
Exemplo n.º 4
0
        private Action SetupBGTcpListenerTask()
        {
            // パケット(プログラムではiSpeed~iVolumeをスキップ)
            //   Int16  iCommand = 0x0001;
            //   Int16  iSpeed = -1;
            //   Int16  iTone = -1;
            //   Int16  iVolume = -1;
            //   Int16  iVoice = 1;
            //   byte   bCode = 0;
            //   Int32  iLength = bMessage.Length;
            //   byte[] bMessage;

            Action BGTcpListen = (() => {
                while (KeepListen) // とりあえずの待ち受け構造
                {
                    try
                    {
                        TcpClient client = TcpIpListener.AcceptTcpClient();
                        Int16 iCommand;
                        Int16 iVoice;
                        int voice;
                        int ListenIf;
                        byte bCode;
                        Int32 iLength;
                        string TalkText = "";

                        byte[] iCommandBuff;
                        byte[] iVoiceBuff;
                        byte[] iLengthBuff;

                        List <int> CidList = Config.AvatorNames.Select(c => c.Key).ToList();
                        int cnt = CidList.Count;
                        int cid;

                        using (NetworkStream ns = client.GetStream())
                        {
                            using (BinaryReader br = new BinaryReader(ns))
                            {
                                iCommandBuff = br.ReadBytes(2);
                                iCommand = BitConverter.ToInt16(iCommandBuff, 0); // コマンド

                                switch (iCommand)
                                {
                                case 0x0001:             // 読み上げ指示

                                    br.ReadBytes(2 * 3); // スキップ

                                    iVoiceBuff = br.ReadBytes(2);
                                    iVoice = BitConverter.ToInt16(iVoiceBuff, 0); // 音声

                                    bCode = br.ReadByte();                        // 文字列エンコーディング

                                    iLengthBuff = br.ReadBytes(4);
                                    iLength = BitConverter.ToInt32(iLengthBuff, 0);     // 文字列サイズ

                                    byte[] TalkTextBuff = new byte[iLength];

                                    TalkTextBuff = br.ReadBytes(iLength);      // 文字列データ

                                    switch (bCode)
                                    {
                                    case 0:         // UTF8
                                        TalkText = System.Text.Encoding.UTF8.GetString(TalkTextBuff, 0, iLength);
                                        break;

                                    case 2:         // CP932
                                        TalkText = System.Text.Encoding.GetEncoding(932).GetString(TalkTextBuff, 0, iLength);
                                        break;

                                    case 1:         // 暫定で書いた
                                        TalkText = System.Text.Encoding.Unicode.GetString(TalkTextBuff, 0, iLength);
                                        break;
                                    }

                                    if (ListenPort == Config.SocketPortNum2)
                                    {
                                        ListenIf = (int)ListenInterface.Socket2;
                                    }
                                    else
                                    {
                                        ListenIf = (int)ListenInterface.Socket1;
                                    }

                                    voice = EditInputText.EditInputString((iVoice > 8 || iVoice == -1 ? 0 : iVoice), TalkText);
                                    cid = UserData.SelectedCid[ListenIf][voice];
                                    switch (UserData.RandomVoiceMethod[ListenIf])
                                    {
                                    case 1:
                                        voice = r.Next(0, 9);
                                        cid = UserData.SelectedCid[ListenIf][voice];
                                        break;

                                    case 2:
                                        cid = CidList[r.Next(0, cnt)];
                                        if (Config.AvatorNames.ContainsKey(cid))
                                        {
                                            UserData.VoiceParams[ListenIf][voice][cid] = Config.AvatorParams(cid);
                                        }
                                        break;
                                    }

                                    Dictionary <string, decimal> Effects = UserData.VoiceParams[ListenIf][voice][cid]["effect"].ToDictionary(k => k.Key, v => v.Value["value"]);
                                    Dictionary <string, decimal> Emotions = UserData.VoiceParams[ListenIf][voice][cid]["emotion"].ToDictionary(k => k.Key, v => v.Value["value"]);

                                    MessageData talk = new MessageData()
                                    {
                                        Cid = cid,
                                        Message = EditInputText.ChangedTalkText,
                                        BouyomiVoice = voice,
                                        ListenInterface = ListenIf,
                                        TaskId = MessQue.count + 1,
                                        Effects = Effects,
                                        Emotions = Emotions
                                    };

                                    switch (PlayMethod)
                                    {
                                    case Methods.sync:
                                        MessQue.AddQueue(talk);
                                        break;

                                    case Methods.async:
                                        OnCallAsyncTalk?.Invoke(talk);
                                        break;
                                    }

                                    break;

                                case 0x0040:     // 読み上げキャンセル
                                    MessQue.ClearQueue();
                                    break;

                                case 0x0110:     // 一時停止状態の取得
                                    byte data1 = 0;
                                    using (BinaryWriter bw = new BinaryWriter(ns))
                                    {
                                        bw.Write(data1);
                                    }
                                    break;

                                case 0x0120:     // 音声再生状態の取得
                                    byte data2 = MessQue.count == 0 ? (byte)0 : (byte)1;
                                    using (BinaryWriter bw = new BinaryWriter(ns))
                                    {
                                        bw.Write(data2);
                                    }
                                    break;

                                case 0x0130:     // 残りタスク数の取得
                                    byte[] data3 = BitConverter.GetBytes(MessQue.count);
                                    using (BinaryWriter bw = new BinaryWriter(ns))
                                    {
                                        bw.Write(data3);
                                    }
                                    break;

                                case 0x0010:     // 一時停止
                                case 0x0020:     // 一時停止の解除
                                case 0x0030:     // 現在の行をスキップし次の行へ
                                default:
                                    break;
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                        //Dispatcher.Invoke(() =>
                        //{
                        //    MessageBox.Show(e.Message, "sorry3");
                        //});
                    }
                }
            });

            return(BGTcpListen);
        }