Exemplo n.º 1
0
        async public Task <int> Reset()
        {
            var dialog = new ContentDialog()
            {
                Title               = AppResources.GetString("Warnning"),
                Content             = AppResources.GetString("AreYouSure"),
                PrimaryButtonText   = AppResources.GetString("Confirm"),
                SecondaryButtonText = AppResources.GetString("Cancel"),
                FullSizeDesired     = false,
            };

            dialog.PrimaryButtonClick += (_s, _e) => { };
            var res = await dialog.ShowAsync();

            if (res.ToString() != "Primary")
            {
                return(0);
            }
            ApplicationView.GetForCurrentView().TryEnterFullScreenMode();
            app_data.ISMUTE       = false;
            app_data.ISNIGHT      = false;
            app_data.ISFULLSCREEN = true;
            app_data.HAVEDONE     = 0;
            app_data.MUSICVOLUME  = app_data.SFXVOLUME = 1;
            app_data.ACHIEVEMENTS = new ObservableCollection <Achievements>();
            app_data.ACHIEVEMENT  = "000000";
            update_views();
            setAchievement();
            update_grid();
            return(0);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Handle events fired when a result is generated. This may include a garbage rule that fires when general room noise
        /// or side-talk is captured (this will have a confidence of Rejected typically, but may occasionally match a rule with
        /// low confidence).
        /// </summary>
        /// <param name="sender">The Recognition session that generated this result</param>
        /// <param name="args">Details about the recognized speech</param>
        private async void ContinuousRecognitionSession_ResultGenerated(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionResultGeneratedEventArgs args)
        {
            // The garbage rule will not have a tag associated with it, the other rules will return a string matching the tag provided
            // when generating the grammar.
            string tag = AppResources.GetString("unknown");

            if (args.Result.Constraint != null)
            {
                tag = args.Result.Constraint.Tag;
            }
            // Developers may decide to use per-phrase confidence levels in order to tune the behavior of their
            // grammar based on testing.
            if (args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
                args.Result.Confidence == SpeechRecognitionConfidence.High)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    edHearState.Text         = $"{AppResources.GetString("Heard")}: {args.Result.Text}, ({AppResources.GetString("Tag")}: {tag}, {AppResources.GetString("Confidence")}: {args.Result.Confidence.ToString()})";
                    edContent.Text          += string.Format("{0}", args.Result.Text);
                    edContent.SelectionStart = edContent.Text.Length;
                });
            }
            else
            {
                // In some scenarios, a developer may choose to ignore giving the user feedback in this case, if speech
                // is not the primary input mechanism for the application.
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    edHearState.Text = $"{AppResources.GetString("VoiceCatchFailed")}. ({AppResources.GetString("Heard")}: {args.Result.Text}, {AppResources.GetString("Tag")}: {tag}, {AppResources.GetString("Confidence")}: {args.Result.Confidence.ToString()})";
                });
            }
        }
 public LevelSucceedDialog()
 {
     this.InitializeComponent();
     Title               = AppResources.GetString("Congratulations");
     passT.Text          = AppResources.GetString("Problemsolved");
     PrimaryButtonText   = AppResources.GetString("PLAYAGAIN");
     SecondaryButtonText = AppResources.GetString("NEXTLEVEL");
 }
Exemplo n.º 4
0
        private async void cbLanguageSelection_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (isPopulatingLanguages)
            {
                return;
            }
            Language targetLang = (Language)(cbLanguageSelection.SelectedItem as ComboBoxItem).Tag;

            await InitializeRecognizer(targetLang);

            edHearState.Text = AppResources.GetString("Idle");
        }
Exemplo n.º 5
0
        public override void Dispose()
        {
            Controller?.RemoveMessage(this, KEY_LEGITIMACY);
            Controller?.RemoveMessage(this, KEY_MULTITHREAD);
            Controller?.SetSubmitButtonEnabled(this, false);
            Controller?.SetThreadLayoutVisibility(this, false);
            Controller?.SetRecommendedName(this, AppResources.GetString("Unknown"), 0.5);
            Controller?.RemoveAnalyser(this);

            _hresp_?.Dispose();
            _hresp_ = null;
            URL     = null;

            GC.Collect();
        }
Exemplo n.º 6
0
 /// <summary>
 /// Handle events fired when error conditions occur, such as the microphone becoming unavailable, or if
 /// some transient issues occur.
 /// </summary>
 /// <param name="sender">The continuous recognition session</param>
 /// <param name="args">The state of the recognizer</param>
 private async void ContinuousRecognitionSession_Completed(SpeechContinuousRecognitionSession sender, SpeechContinuousRecognitionCompletedEventArgs args)
 {
     if (args.Status != SpeechRecognitionResultStatus.Success)
     {
         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {
             edHearState.Text              = $"{AppResources.GetString("RecognitionCompleted")} {AppResources.GetString(args.Status.ToString())}";
             BtnCancel.Visibility          = Visibility.Collapsed;
             btnListen.Content             = AppResources.GetString("Listen");
             btnListen.IsChecked           = false;
             cbLanguageSelection.IsEnabled = true;
             isListening = false;
         });
     }
 }
Exemplo n.º 7
0
 /// <summary>
 /// Provide feedback to the user based on whether the recognizer is receiving their voice input.
 /// </summary>
 /// <param name="sender">The recognizer that is currently running.</param>
 /// <param name="args">The current state of the recognizer.</param>
 private async void SpeechRecognizer_StateChanged(SpeechRecognizer sender, SpeechRecognizerStateChangedEventArgs args)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         var state        = args.State.ToString().Trim();
         edHearState.Text = AppResources.GetString(state);
         //rootPage.NotifyUser(args.State.ToString(), NotifyType.StatusMessage);
         if (state.Equals("Idle", StringComparison.CurrentCultureIgnoreCase))
         {
             btnListen.Content             = AppResources.GetString("Listen");
             btnListen.IsChecked           = false;
             cbLanguageSelection.IsEnabled = true;
             isListening = false;
         }
     });
 }
Exemplo n.º 8
0
        public async void success()
        {
            BGMPlayer.PlayButton8();
            LevelSucceedDialog lsd = new LevelSucceedDialog();

            APPDATA.app_data.HAVEDONE = Math.Max(APPDATA.app_data.HAVEDONE, localLevel.ID);
            var ach = APPDATA.app_data.ACHIEVEMENT;

            APPDATA.app_data.setAchievement();
            for (int i = 0; i < 6; i++)
            {
                if (ach[i] == '0' && APPDATA.app_data.ACHIEVEMENT[i] == '1')
                {
                    CONST.ShowToastNotification("Square150x150Logo.scale-200.png", AppResources.GetString("isunlock"), NotificationAudioNames.Default);
                }
            }

            var res = await lsd.ShowAsync();

            if (res.ToString() == "Primary")
            {
                //APPDATA.app_data.MoveTo(AppPage.GamePage,localLevel);
            }
            else
            {
                if (localLevel.ID % 9 == 0)
                {
                    APPDATA.app_data.MoveTo(AppPage.SelectChapterPage);
                    var c = SelectGame.localChapter;
                    if (c.ID >= APPDATA.app_data.Chapters.Count)
                    {
                        return;
                    }
                    APPDATA.app_data.Chapters[c.ID].unlocked = 1;
                    return;
                }
                var levels = Level.getLevels(SelectGame.localChapter.ID);
                foreach (var l in levels)
                {
                    if (l.ID == localLevel.ID + 1)
                    {
                        APPDATA.app_data.MoveTo(AppPage.GamePage, l);
                    }
                }
            }
        }
Exemplo n.º 9
0
        public static ObservableCollection <Level> getLevels(int start = 1)
        {
            start = 1 + start * 9 - 9;
            ObservableCollection <Level> levels = new ObservableCollection <Level>();

            for (int i = start; i < start + 9; i++)
            {
                Level x = new Level(i);
                x.name     = AppResources.GetString("L" + x.ID.ToString() + "N");
                x.Discribe = AppResources.GetString("L" + x.ID.ToString() + "D");
                x.cover    = "ms-appx:///Pictures/Levels/" + x.ID.ToString() + ".png";
                if (APPDATA.app_data.HAVEDONE >= x.ID - 1)
                {
                    x.unlocked = 1;
                }
                levels.Add(x);
            }
            return(levels);
        }
Exemplo n.º 10
0
 private void BtnCancel_Click(object sender, RoutedEventArgs e)
 {
     if (media != null)
     {
         media.Stop();
     }
     if (synth != null)
     {
         synth = null;
     }
     if (canceltsrc != null)
     {
         canceltsrc.Cancel();
         edHearState.Text = AppResources.GetString("Canceled");
     }
     btnSpeak.IsChecked   = false;
     btnListen.IsChecked  = false;
     BtnCancel.Visibility = Visibility.Collapsed;
 }
Exemplo n.º 11
0
        public override async Task SetURLAsync(string url)
        {
            URL = Converters.UrlConverter.TranslateURLThunder(url);
            Controller?.UpdateMessage(this, KEY_THUNDER, new PlainTextMessage(
                                          AppResources.GetString("ThunderLinkDetected")));
            innerAnalyser?.Dispose();
            innerAnalyser = null;
            innerAnalyser = Converters.UrlConverter.GetAnalyser(URL);
            if (innerAnalyser == null)
            {
                Controller?.UpdateMessage(this, KEY_THUNDER, new PlainTextMessage(
                                              AppResources.GetString("ThunderLinkDetectedButFailed")));
                return;
            }

            Controller?.RegistAnalyser(this, innerAnalyser);
            innerAnalyser.BindVisualController(Controller);
            await innerAnalyser.SetURLAsync(URL);
        }
Exemplo n.º 12
0
        public static ObservableCollection <Achievements> GetAch(double ff = 44)
        {
            var ach = new ObservableCollection <Achievements>();

            for (int i = 0; i < 6; i++)
            {
                ach.Add(new Achievements());
                ach[i].name     = AppResources.GetString("AC" + (i + 1).ToString() + "N");
                ach[i].discribe = AppResources.GetString("AC" + (i + 1).ToString() + "D");
                string locked = APPDATA.app_data.ACHIEVEMENT[i] == '0' ? "Lock" : "Unlock";
                if (APPDATA.app_data.ACHIEVEMENT[i] == '1')
                {
                    ach[i].col = new SolidColorBrush(Color.FromArgb(255, 1, 139, 61));
                }
                ach[i].islock  = AppResources.GetString(locked);
                ach[i].picture = "ms-appx:///Pictures/Achievement/" + (i + 1).ToString() + ".png";
            }
            return(ach);
        }
Exemplo n.º 13
0
        public static ObservableCollection <Chapter> getChapters()
        {
            ObservableCollection <Chapter> k = new ObservableCollection <Chapter>();

            k.Add(new Chapter(1));
            k.Add(new Chapter(2));
            k.Add(new Chapter(3));
            foreach (var x in k)
            {
                x.name     = AppResources.GetString("CN" + x.ID.ToString());
                x.discribe = AppResources.GetString("CD" + x.ID.ToString());
                x.cover    = "ms-appx:///Pictures/Chapters/" + x.ID.ToString() + ".png";
                int hvdone = (APPDATA.app_data.HAVEDONE - 1) / 9;
                if (x.ID - 1 <= hvdone)
                {
                    x.unlocked = 1;
                }
                x.Levels = Level.getLevels(x.ID);
            }
            return(k);
        }
Exemplo n.º 14
0
        private async Task <string> InputBox(string caption)
        {
            TextBox edInput = new TextBox();

            edInput.AcceptsReturn = false;
            edInput.Height        = 32;
            ContentDialog dialog = new ContentDialog();

            dialog.Content = edInput;
            dialog.Title   = caption;
            dialog.IsSecondaryButtonEnabled = true;
            dialog.PrimaryButtonText        = AppResources.GetString("OK");
            dialog.SecondaryButtonText      = AppResources.GetString("Cancel");
            if (await dialog.ShowAsync() == ContentDialogResult.Primary)
            {
                return(edInput.Text);
            }
            else
            {
                return(string.Empty);
            }
        }
Exemplo n.º 15
0
        private async void BtnSaveAs_Click(object sender, RoutedEventArgs e)
        {
            // Generate the audio stream from plain text.
            if (edContent.Text.Length <= 0)
            {
                return;
            }
            string contents = string.Empty;

            if (edContent.SelectionLength > 0)
            {
                contents = edContent.SelectedText;
            }
            else if (edContent.SelectionStart >= edContent.Text.Length)
            {
                contents = edContent.Text;
            }
            else
            {
                contents = edContent.Text.Substring(edContent.SelectionStart);
            }

            //bool split = (bool)ChkAutoSplit.IsChecked;
            try
            {
                int split = Convert.ToInt32(edSplit.Text.Trim());
                await Text2Audio(contents, split);
            }
            catch (Exception ex)
            {
                MessageDialog msg = new MessageDialog($"{AppResources.GetString("InputError")}: {ex.ToString()}", AppResources.GetString("Error"));
                msg.Commands.Add(new UICommand(AppResources.GetString("OK"), cmd => { }, ContentDialogResult.Primary));
                msg.DefaultCommandIndex = 0;
                msg.CancelCommandIndex  = 0;
                await msg.ShowAsync();
            }
        }
Exemplo n.º 16
0
        public override async Task SetURLAsync(string url)
        {
            URL = url;

            Controller?.SetRecommendedName(this, Path.GetFileName(url), 0.5);
            Controller?.UpdateMessage(this, KEY_LEGITIMACY,
                                      new PlainTextMessage(AppResources.GetString("Connecting")));

            await GetResponseAsync();

            if (_hresp_ == null)
            {
                Controller?.UpdateMessage(this, KEY_LEGITIMACY,
                                          new PlainTextMessage(AppResources.GetString("UnableToConnect")));
            }
            else
            {
                Controller?.UpdateMessage(this, KEY_LEGITIMACY,
                                          new PlainTextMessage(AppResources.GetString("SuccessfullyConnected")));
                Controller?.SetSubmitButtonEnabled(this, true);

                if (GetStreamSize() > 0)
                {
                    Controller?.SetThreadLayoutVisibility(this, true);
                    Controller?.UpdateMessage(this, KEY_MULTITHREAD,
                                              new PlainTextMessage(AppResources.GetString("Multithread")));
                }
                else
                {
                    Controller?.SetThreadLayoutVisibility(this, false);
                    Controller?.RemoveMessage(this, KEY_MULTITHREAD);
                }

                Controller?.SetRecommendedName(this, GetRecommendedName(), 1);
            }
        }
Exemplo n.º 17
0
        private async void BtnListen_Click(object sender, RoutedEventArgs e)
        {
            btnListen.IsEnabled = false;
            if (isListening == false)
            {
                if (media != null)
                {
                    media.Stop();
                }
                if (synth != null)
                {
                    synth = null;
                }

                // The recognizer can only start listening in a continuous fashion if the recognizer is currently idle.
                // This prevents an exception from occurring.
                if (recognizer.State == SpeechRecognizerState.Idle)
                {
                    try
                    {
                        await recognizer.ContinuousRecognitionSession.StartAsync();

                        //recognizer.UIOptions.
                        cbLanguageSelection.IsEnabled = false;
                        btnListen.Content             = $"{AppResources.GetString("Listen")}...";
                        btnListen.IsChecked           = true;
                        btnSpeak.IsChecked            = false;
                        BtnCancel.Visibility          = Visibility.Visible;
                        isListening = true;
                    }
                    catch (System.Runtime.InteropServices.COMException ex) when(ex.HResult == unchecked ((int)0x80045509))
                    {
                        //privacyPolicyHResult
                        //The speech privacy policy was not accepted prior to attempting a speech recognition.
                        ContentDialog dlgWarning = new ContentDialog()
                        {
                            Title               = AppResources.GetString("SpeechPrivacyTitle"),
                            Content             = AppResources.GetString("SpeechPrivacyContent"),
                            PrimaryButtonText   = AppResources.GetString("SpeechPrivacyPriButton"),
                            SecondaryButtonText = AppResources.GetString("SpeechPrivacySecButton")
                        };
                        var result = await dlgWarning.ShowAsync();

                        if (result == ContentDialogResult.Secondary)
                        {
                            const string uriToLaunch = "ms-settings:privacy-speechtyping";
                            //"http://stackoverflow.com/questions/42391526/exception-the-speech-privacy-policy-" +
                            //"was-not-accepted-prior-to-attempting-a-spee/43083877#43083877";
                            var uri = new Uri(uriToLaunch);

                            var success = await Windows.System.Launcher.LaunchUriAsync(uri);

                            if (!success)
                            {
                                await new ContentDialog
                                {
                                    Title             = AppResources.GetString("SpeechPrivacyResultTitle"),
                                    Content           = AppResources.GetString("SpeechPrivacyResultContent"),
                                    PrimaryButtonText = AppResources.GetString("SpeechPrivacyResultPriButton")
                                }.ShowAsync();
                                btnListen.Visibility = Visibility.Collapsed;
                            }
                        }
                        else if (result == ContentDialogResult.Primary)
                        {
                            btnListen.Visibility = Visibility.Collapsed;
                        }
                    }
                    catch (Exception ex)
                    {
                        var messageDialog = new MessageDialog(ex.Message, AppResources.GetString("Exception"));
                        await messageDialog.ShowAsync();
                    }
                }
            }
            else
            {
                isListening = false;
                cbLanguageSelection.IsEnabled = true;
                if (recognizer.State != SpeechRecognizerState.Idle)
                {
                    try
                    {
                        // Cancelling recognition prevents any currently recognized speech from
                        // generating a ResultGenerated event. StopAsync() will allow the final session to
                        // complete.
                        await recognizer.ContinuousRecognitionSession.CancelAsync();

                        btnListen.Content    = AppResources.GetString("Listen");
                        btnListen.IsChecked  = false;
                        BtnCancel.Visibility = Visibility.Collapsed;
                    }
                    catch (Exception ex)
                    {
                        var messageDialog = new MessageDialog(ex.Message, AppResources.GetString("Exception"));
                        await messageDialog.ShowAsync();
                    }
                }
            }
            btnListen.IsEnabled = true;
        }
Exemplo n.º 18
0
        private async Task Text2Audio(string text, StorageFile audio)
        {
            if (audio != null && !string.IsNullOrEmpty(text))
            {
                if (synth == null)
                {
                    synth = new SpeechSynthesizer();
                }
                var voice = SpeechSynthesizer.AllVoices.Where(o => o.DisplayName == (string)cbVoice.SelectedItem);
                synth.Voice = voice.First();
                synth.Options.AudioPitch   = sliderPitch.Value;
                synth.Options.AudioVolume  = sliderVolume.Value / 100.0;
                synth.Options.SpeakingRate = sliderSpeed.Value;
                //var options = new SpeechSynthesizerOptions();

                SpeechSynthesisStream stream = await synth.SynthesizeTextToStreamAsync(text);

                trans = new MediaTranscoder()
                {
                    HardwareAccelerationEnabled = true,
                    AlwaysReencode = true,
                    //VideoProcessingAlgorithm = MediaVideoProcessingAlgorithm.MrfCrf444;
                };

                MediaEncodingProfile profile = MediaEncodingProfile.CreateMp3(AudioEncodingQuality.Medium);
                if (audio.ContentType.EndsWith("wav", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateWav(AudioEncodingQuality.Medium);
                }
                else if (audio.ContentType.EndsWith("aac", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Medium);
                }
                else if (audio.ContentType.EndsWith("m4a", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateM4a(AudioEncodingQuality.Medium);
                }
                else if (audio.FileType.EndsWith("alac", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateAlac(AudioEncodingQuality.Medium);
                }
                else if (audio.ContentType.EndsWith("flac", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateFlac(AudioEncodingQuality.Medium);
                }
                else if (audio.ContentType.EndsWith("mp4", StringComparison.CurrentCultureIgnoreCase))
                {
                    profile = MediaEncodingProfile.CreateMp4(VideoEncodingQuality.Pal);
                }

                using (IRandomAccessStream fso = await audio.OpenAsync(FileAccessMode.ReadWrite))
                {
                    //var trans_result = await trans.PrepareFileTranscodeAsync(InFile, OutFile, profile_mp3);
                    var trans_result = await trans.PrepareStreamTranscodeAsync(stream, fso, profile);

                    if (trans_result.CanTranscode)
                    {
                        if (canceltsrc != null)
                        {
                            canceltsrc.Dispose();
                            canceltsrc = null;
                        }
                        canceltsrc = new CancellationTokenSource();
                        var progress = new Progress <double>(ps =>
                        {
                            edHearState.Text = $"{AppResources.GetString("ProcessingState")} {ps:N0}%";
                            //edHearState.Text = AppResources.GetString("ProcessingState");
                        });
                        await trans_result.TranscodeAsync().AsTask(canceltsrc.Token, progress);

                        edHearState.Text = AppResources.GetString("ProcessFinished");
                    }
                    else
                    {
                        edHearState.Text = AppResources.GetString("CanNotTrans");
                    }
                }
            }
        }
Exemplo n.º 19
0
        private async Task Text2Audio(string text, int split = 0)
        {
            // Generate the audio stream from plain text.
            if (edContent.Text.Length <= 0)
            {
                return;
            }
            string contents = string.Empty;

            if (edContent.SelectionLength > 0)
            {
                contents = edContent.SelectedText;
            }
            else if (edContent.SelectionStart >= edContent.Text.Length)
            {
                contents = edContent.Text;
            }
            else
            {
                contents = edContent.Text.Substring(edContent.SelectionStart);
            }

            if (split > 0)
            {
                string[] splitChar = new string[] { ".", "。", "?", "?", "!", "!" };

                FolderPicker fp = new FolderPicker();
                //fp.SuggestedStartLocation = PickerLocationId.Desktop;
                fp.FileTypeFilter.Add("*");
                var TargetFolder = await fp.PickSingleFolderAsync();

                if (TargetFolder != null)
                {
                    StorageApplicationPermissions.MostRecentlyUsedList.Add(TargetFolder, TargetFolder.Name);
                    if (StorageApplicationPermissions.FutureAccessList.Entries.Count >= 1000)
                    {
                        StorageApplicationPermissions.FutureAccessList.Remove(StorageApplicationPermissions.FutureAccessList.Entries.Last().Token);
                    }
                    StorageApplicationPermissions.FutureAccessList.Add(TargetFolder, TargetFolder.Name);

                    var ffn = await InputBox(AppResources.GetString("InputFileName"));

                    if (string.IsNullOrEmpty(ffn))
                    {
                        return;
                    }

                    //await ProgressRingBox(AppResources.GetString("Waiting"));
                    ProgressRing.Visibility = Visibility.Visible;
                    ProgressRing.IsActive   = true;

                    var fn  = Path.GetFileNameWithoutExtension(ffn);
                    var ext = Path.GetExtension(ffn);
                    if (string.IsNullOrEmpty(ext))
                    {
                        ext = ".mp3";
                    }

                    List <string> paras = new List <string>();
                    string[]      lines = text.Split(splitChar, StringSplitOptions.RemoveEmptyEntries);
                    StringBuilder sb    = new StringBuilder();
                    foreach (string t in lines)
                    {
                        sb.AppendLine(t);
                        if (sb.Length >= split)
                        {
                            paras.Add(sb.ToString());
                            sb.Clear();
                        }
                    }

                    int count = 0;
                    foreach (var line in paras)
                    {
                        var suffix = $"{count}";
                        if (paras.Count > 10000)
                        {
                            suffix = $"{count:d05}";
                        }
                        else if (paras.Count >= 1000)
                        {
                            suffix = $"{count:d04}";
                        }
                        else if (paras.Count >= 100)
                        {
                            suffix = $"{count:d03}";
                        }
                        else if (paras.Count >= 10)
                        {
                            suffix = $"{count:d02}";
                        }

                        StorageFile fo = await TargetFolder.CreateFileAsync($"{fn}_{suffix}{ext}", CreationCollisionOption.ReplaceExisting);
                        await Text2Audio(line, fo);

                        count++;
                    }
                }
            }
            else
            {
                FileSavePicker fsp = new FileSavePicker();
                fsp.DefaultFileExtension = ".mp3";
                fsp.FileTypeChoices.Add("MP3 file", new List <string>()
                {
                    ".mp3"
                });
                fsp.FileTypeChoices.Add("AAC/M4A file", new List <string>()
                {
                    ".aac", ".m4a"
                });
                fsp.FileTypeChoices.Add("FLAC file", new List <string>()
                {
                    ".flac"
                });
                fsp.FileTypeChoices.Add("ALAC file", new List <string>()
                {
                    ".alac"
                });
                fsp.FileTypeChoices.Add("WAV file", new List <string>()
                {
                    ".wav"
                });
                fsp.FileTypeChoices.Add("MP4 file", new List <string>()
                {
                    ".mp4"
                });
                fsp.SuggestedFileName = "untitled";

                OutFile = await fsp.PickSaveFileAsync();

                ProgressRing.Visibility = Visibility.Visible;
                ProgressRing.IsActive   = true;
                await Text2Audio(contents, OutFile);
            }
            ProgressRing.IsActive   = false;
            ProgressRing.Visibility = Visibility.Collapsed;
        }
Exemplo n.º 20
0
        public override async Task SetURLAsync(string url)
        {
            try
            {
                id = YoutubeClient.ParseVideoId(url);
                var client = new YoutubeClient();
                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(AppResources.GetString("YouTubeLinkDetectedButWaiting")));
                video = await client.GetVideoAsync(id);

                infos = await client.GetVideoMediaStreamInfosAsync(id);

                if (infos.Muxed.Count > 0)
                {
                    Controller?.SetComboBoxLayoutVisibility(this, true);
                }
                else
                {
                    throw new Exception();
                }

                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(
                                              AppResources.GetString("YouTubeLinkDetectedButWaiting")
                                              + " - " +
                                              video.Title
                                              ));

                foreach (var info in infos.Muxed)
                {
                    PlainTextComboBoxData data = new PlainTextComboBoxData();
                    data.Text = info.VideoQuality.ToString() + " - " + info.VideoEncoding.ToString();
                    Controller?.AddComboBoxItem(this, data);
                }

                Controller?.SetComboBoxSelectionChangedListener(this,
                                                                async(item) => {
                    innerAnalyser?.Dispose();
                    string target = GetURLFromInfos(item.Text);
                    if (target != null)
                    {
                        innerAnalyser = Converters.UrlConverter.GetAnalyser(target);
                        if (innerAnalyser != null)
                        {
                            URL = target;
                            innerAnalyser.BindVisualController(Controller);
                            Controller?.RegistAnalyser(this, innerAnalyser);
                            await innerAnalyser.SetURLAsync(target);
                        }
                    }
                }
                                                                );
            }
            catch (Exception)
            {
                Controller?.UpdateMessage(this, KEY_YOUTUBE,
                                          new PlainTextMessage(
                                              AppResources.GetString("YouTubeLinkDetectedButFailed")
                                              ));
                Controller?.SetComboBoxLayoutVisibility(this, false);
            }
        }
Exemplo n.º 21
0
        /// <summary>
        /// Initialize Speech Recognizer and compile constraints.
        /// </summary>
        /// <param name="recognizerLanguage">Language to use for the speech recognizer</param>
        /// <returns>Awaitable task.</returns>
        private async Task InitializeRecognizer(Language recognizerLanguage)
        {
            if (recognizer != null)
            {
                // cleanup prior to re-initializing this scenario.
                recognizer.StateChanged -= SpeechRecognizer_StateChanged;
                recognizer.ContinuousRecognitionSession.Completed       -= ContinuousRecognitionSession_Completed;
                recognizer.ContinuousRecognitionSession.ResultGenerated -= ContinuousRecognitionSession_ResultGenerated;

                this.recognizer.Dispose();
                this.recognizer = null;
            }

            try
            {
                this.recognizer = new SpeechRecognizer(recognizerLanguage);

                // Provide feedback to the user about the state of the recognizer. This can be used to provide visual feedback in the form
                // of an audio indicator to help the user understand whether they're being heard.
                recognizer.StateChanged += SpeechRecognizer_StateChanged;

                //// Build a command-list grammar. Commands should ideally be drawn from a resource file for localization, and
                //// be grouped into tags for alternate forms of the same command.
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString
                //        }, "Home"));
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString
                //        }, "GoToContosoStudio"));
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString,
                //        speechResourceMap.GetValue("ListGrammarOpenMessage", speechContext).ValueAsString
                //        }, "Message"));
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarSendEmail", speechContext).ValueAsString,
                //        speechResourceMap.GetValue("ListGrammarCreateEmail", speechContext).ValueAsString
                //        }, "Email"));
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarCallNitaFarley", speechContext).ValueAsString,
                //        speechResourceMap.GetValue("ListGrammarCallNita", speechContext).ValueAsString
                //        }, "CallNita"));
                //recognizer.Constraints.Add(
                //    new SpeechRecognitionListConstraint(
                //        new List<string>()
                //        {
                //        speechResourceMap.GetValue("ListGrammarCallWayneSigmon", speechContext).ValueAsString,
                //        speechResourceMap.GetValue("ListGrammarCallWayne", speechContext).ValueAsString
                //        }, "CallWayne"));

                //// Update the help text in the UI to show localized examples
                //string uiOptionsText = string.Format("Try saying '{0}', '{1}' or '{2}'",
                //    speechResourceMap.GetValue("ListGrammarGoHome", speechContext).ValueAsString,
                //    speechResourceMap.GetValue("ListGrammarGoToContosoStudio", speechContext).ValueAsString,
                //    speechResourceMap.GetValue("ListGrammarShowMessage", speechContext).ValueAsString);
                ////listGrammarHelpText.Text = string.Format("{0}\n{1}",
                ////    speechResourceMap.GetValue("ListGrammarHelpText", speechContext).ValueAsString,
                ////    uiOptionsText);

                SpeechRecognitionCompilationResult result = await recognizer.CompileConstraintsAsync();

                if (result.Status != SpeechRecognitionResultStatus.Success)
                {
                    // Disable the recognition buttons.
                    btnListen.IsEnabled = false;

                    // Let the user know that the grammar didn't compile properly.
                    edHearState.Text = AppResources.GetString("UnableCompileGrammar");
                }
                else
                {
                    btnListen.IsEnabled = true;

                    // Handle continuous recognition events. Completed fires when various error states occur. ResultGenerated fires when
                    // some recognized phrases occur, or the garbage rule is hit.
                    recognizer.ContinuousRecognitionSession.Completed       += ContinuousRecognitionSession_Completed;
                    recognizer.ContinuousRecognitionSession.ResultGenerated += ContinuousRecognitionSession_ResultGenerated;
                }
            }
            catch (Exception ex)
            {
                if ((uint)ex.HResult == HResultRecognizerNotFound)
                {
                    btnListen.IsEnabled = false;

                    edHearState.Visibility = Visibility.Visible;
                    edHearState.Text       = AppResources.GetString("SpeechLanguageNotInstalled");
                }
                else
                {
                    var messageDialog = new Windows.UI.Popups.MessageDialog(ex.Message, AppResources.GetString("Exception"));
                    await messageDialog.ShowAsync();
                }
            }
        }
Exemplo n.º 22
0
        public override string GetRecommendedName()
        {
            if (_hresp_ == null)
            {
                return(null);
            }
            //https://blog.csdn.net/ash292340644/article/details/52412674
            try
            {
                string fileinfo = (_hresp_).Headers["Content-Disposition"];
                string mathkey  = "filename=";
                //当response头中没有Content-Disposition信息时返回从url中截取的文件名
                string name = null;
                if (fileinfo != null)
                {
                    name = fileinfo.Substring(fileinfo.LastIndexOf(mathkey)).Replace(mathkey, "");
                }
                else
                {
                    name = Path.GetFileName(_hresp_.ResponseUri.OriginalString);
                }
                //name是从链接中分析到的全名
                string contentType = _hresp_.ContentType;
                if (contentType.Contains(';'))
                {
                    contentType = contentType.Split(';')[0];
                }
                if (name.Length >= 32)
                {
                    name = name.Substring(name.Length - 32);
                }
                //根据contentType推测扩展名
                if (contentType == null)
                {
                    contentType = "text/html";
                }
                string[] rec_exts = new string[0];
                if (Converters.ExtentionConverter.Dictionary != null &&
                    Converters.ExtentionConverter.Dictionary.ContainsKey(contentType))
                {
                    rec_exts = Converters.ExtentionConverter.Dictionary[contentType].Split('#');
                }
                //判断是否有一个和文件名相符
                foreach (string ext in rec_exts)
                {
                    if (name.EndsWith(ext))
                    {
                        return(name);
                    }
                }

                //如果rec_exts不为空,显示一条提示给用户
                if (rec_exts.Length != 0)
                {
                    string message = AppResources.GetString("RecommendTypeMessage") + String.Join(" ", rec_exts);
                    Controller?.UpdateMessage(this, KEY_RECOMMENDED_TYPES,
                                              new PlainTextMessage(message));
                }

                //没有和文件名相符的,判断文件名是否含后缀
                if (name.Contains('.'))
                {
                    return(name);
                }
                else if (rec_exts.Length != 0)
                {
                    return(name + rec_exts[0]);
                }
                else
                {
                    return(name + ".unknown");
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }