Exemplo n.º 1
0
        private void SetDefaultLanguageNonLollipop()
        {
            //disable warning because we are checking ahead of time.
#pragma warning disable 0618
            var sdk = (int)global::Android.OS.Build.VERSION.SdkInt;
            if (sdk >= 18)
            {
#if __ANDROID_18__
                if (textToSpeech.DefaultLanguage == null && textToSpeech.Language != null)
                {
                    textToSpeech.SetLanguage(textToSpeech.Language);
                }
                else if (textToSpeech.DefaultLanguage != null)
                {
                    textToSpeech.SetLanguage(textToSpeech.DefaultLanguage);
                }
#endif
            }
            else
            {
                if (textToSpeech.Language != null)
                {
                    textToSpeech.SetLanguage(textToSpeech.Language);
                }
            }
#pragma warning restore 0618
        }
Exemplo n.º 2
0
        private void SetDefaultLanguageNonLollipop()
        {
            //disable warning because we are checking ahead of time.
#pragma warning disable 0618
            if (textToSpeech.DefaultLanguage == null && textToSpeech.Language != null)
            {
                textToSpeech.SetLanguage(textToSpeech.Language);
            }
            else if (textToSpeech.DefaultLanguage != null)
            {
                textToSpeech.SetLanguage(textToSpeech.DefaultLanguage);
            }
#pragma warning restore 0618
        }
Exemplo n.º 3
0
        /// <summary>
        /// Process results from started activities.
        /// </summary>
        protected override void OnActivityResult(int requestCode, int resultCode, Intent data)
        {
            if (requestCode == RECOGNIZER_RESULT && resultCode == RESULT_OK)
            {
                var matches = data.GetStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);

                var speechText = FindViewById<TextView>(R.Ids.speechText);
                recognizedText = matches.Get(0);
                speechText.SetText(recognizedText);

                var checkIntent = new Intent();
                checkIntent.SetAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
                StartActivityForResult(checkIntent, SPEECH_RESULT);
            }

            if (requestCode == SPEECH_RESULT)
            {
                if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS)
                {
                    textToSpeech = new TextToSpeech(this, this);
                    textToSpeech.SetLanguage(Locale.US);
                }
                else
                {
                    // TTS data not yet loaded, try to install it
                    var ttsLoadIntent = new Intent();
                    ttsLoadIntent.SetAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
                    StartActivity(ttsLoadIntent);
                }
            }
            base.OnActivityResult(requestCode, resultCode, data);
        }
Exemplo n.º 4
0
 public void OnInit(OperationResult status)
 {
     if (status.Equals(OperationResult.Success))
     {
         speaker.SetLanguage(Settings.CurrentPronunciation == $"{Pronunciation.en}" ? Locale.Us : Locale.Uk);
         speaker.Speak(ToSpeak, QueueMode.Flush, null, null);
     }
 }
Exemplo n.º 5
0
        private void SetDefaultLanguage()
        {
            int  version    = (int)global::Android.OS.Build.VERSION.SdkInt;
            bool isLollipop = version >= 21;

            if (isLollipop)
            {
                //in a different method as it can crash on older target/compile for some reason
                SetDefaultLanguageLollipop();
            }
            else
            {
                //disable warning because we are checking ahead of time.
#pragma warning disable 0618
                if (textToSpeech.DefaultLanguage == null)
                {
                    textToSpeech.SetLanguage(textToSpeech.Language);
                }
                textToSpeech.SetLanguage(textToSpeech.DefaultLanguage);
#pragma warning restore 0618
            }
        }
Exemplo n.º 6
0
		public void Speak (string text)
		{
			var c = Forms.Context; 
			toSpeak = text;
			if (speaker == null) {
				speaker = new TextToSpeech (c, this);
				var languageIso = "en_GB";
				var locale = new Java.Util.Locale(languageIso);// languageIso is locale string
				speaker.SetLanguage (locale);
			}
			else
			{
				var p = new Dictionary<string,string> ();
				speaker.Speak (toSpeak, QueueMode.Flush, p);
			}
        }
        /// <summary>
        ///     The speak.
        /// </summary>
        /// <param name="text">
        ///     The text.
        /// </param>
        public void Speak (string text, string language = DefaultLocale)
        {
            _toSpeak = text;
            if (_speaker == null)
            {
                _speaker = new TextToSpeech(Context, this);

                var lang = GetInstalledLanguages().Where(c => c == language).DefaultIfEmpty(DefaultLocale).First();
                var locale = new Locale (lang);
                _speaker.SetLanguage (locale);
            }
            else
            {
                var p = new Dictionary<string, string>();
                _speaker.Speak(_toSpeak, QueueMode.Flush, p);
            }
        }
		/// <summary>
		/// The speak.
		/// </summary>
		/// <param name="text">The text.</param>
		/// <param name="language">The language.</param>
		public void Speak (string text, string language = DefaultLocale)
        {
            _toSpeak = text;
            if (_speaker == null)
            {
                _speaker = new TextToSpeech(Context, this);

                var lang = GetInstalledLanguages().Where(c => c == language).DefaultIfEmpty(DefaultLocale).First();
                var locale = new Locale (lang);
                _speaker.SetLanguage (locale);
            }
            else
            {
                var p = new Dictionary<string, string>();

#pragma warning disable CS0618 // Type or member is obsolete
				_speaker.Speak(_toSpeak, QueueMode.Flush, p);
#pragma warning restore CS0618 // Type or member is obsolete
			}
        }
        public async Task SpeakAsync(string text, int max, SpeechOptions options, CancellationToken cancelToken)
        {
            await Initialize();

            // Wait for any previous calls to finish up
            if (tcsUtterances?.Task != null)
            {
                await tcsUtterances.Task;
            }

            if (cancelToken != null)
            {
                cancelToken.Register(() =>
                {
                    try
                    {
                        tts?.Stop();

                        tcsUtterances?.TrySetResult(true);
                    }
                    catch
                    {
                    }
                });
            }

            if (options?.Locale?.Language != null)
            {
                JavaLocale locale = null;
                if (!string.IsNullOrWhiteSpace(options?.Locale.Country))
                {
                    locale = new JavaLocale(options.Locale.Language, options.Locale.Country);
                }
                else
                {
                    locale = new JavaLocale(options.Locale.Language);
                }

                tts.SetLanguage(locale);
            }
            else
            {
                SetDefaultLanguage();
            }

            if (options?.Pitch.HasValue ?? false)
            {
                tts.SetPitch(options.Pitch.Value);
            }
            else
            {
                tts.SetPitch(TextToSpeech.PitchDefault);
            }

            tts.SetSpeechRate(1.0f);

            var parts = text.SplitSpeak(max);

            numExpectedUtterances = parts.Count;
            tcsUtterances         = new TaskCompletionSource <bool>();

            var guid = Guid.NewGuid().ToString();

            for (var i = 0; i < parts.Count && !cancelToken.IsCancellationRequested; i++)
            {
                // We require the utterance id to be set if we want the completed listener to fire
                var map = new Dictionary <string, string>
                {
                    { AndroidTextToSpeech.Engine.KeyParamUtteranceId, $"{guid}.{i}" }
                };

                if (options != null && options.Volume.HasValue)
                {
                    map.Add(AndroidTextToSpeech.Engine.KeyParamVolume, options.Volume.Value.ToString(CultureInfo.InvariantCulture));
                }

                // We use an obsolete overload here so it works on older API levels at runtime
                // Flush on first entry and add (to not flush our own previous) subsequent entries
#pragma warning disable CS0618
                tts.Speak(parts[i], i == 0 ? QueueMode.Flush : QueueMode.Add, map);
#pragma warning restore CS0618
            }

            await tcsUtterances.Task;
        }
		protected override void OnCreate(Bundle bundle)
		{
			base.OnCreate(bundle);

			// Set our view from the "main" layout resource
			SetContentView(Resource.Layout.Main);

			// we need to register the onscreen gadgets we're interested in

			var btnSayIt = FindViewById<Button>(Resource.Id.btnSpeak);
			var editWhatToSay = FindViewById<EditText>(Resource.Id.editSpeech);
			var spinLanguages = FindViewById<Spinner>(Resource.Id.spinLanguage);
			var txtSpeedVal = FindViewById<TextView>(Resource.Id.textSpeed);
			var txtPitchVal = FindViewById<TextView>(Resource.Id.textPitch);
			var seekSpeed = FindViewById<SeekBar>(Resource.Id.seekSpeed);
			var seekPitch = FindViewById<SeekBar>(Resource.Id.seekPitch);

			// set up the initial pitch and speed values then the onscreen values
			// the pitch and rate both go from 0f to 1f, however if you have a seek bar with a max of 1, you get a single step
			// therefore, a simpler option is to have the slider go from 0 to 255 and divide the position of the slider by 255 to get
			// the float
			seekSpeed.Progress = seekPitch.Progress = 127;
			txtSpeedVal.Text = txtPitchVal.Text = "0.5";

			// get the context - easiest way is to obtain it from an on screen gadget
			context = btnSayIt.Context;

			// set up the TextToSpeech object
			// third parameter is the speech engine to use
			textToSpeech = new TextToSpeech(this, this, "com.google.android.tts");

			// set up the langauge spinner
			// set the top option to be default
			var langAvailable = new List<string>{ "Default" };

			// our spinner only wants to contain the languages supported by the tts and ignore the rest
			var localesAvailable = Java.Util.Locale.GetAvailableLocales().ToList();
			foreach (var locale in localesAvailable)
			{
				LanguageAvailableResult res = textToSpeech.IsLanguageAvailable(locale);
				switch (res)
				{
				case LanguageAvailableResult.Available:
					langAvailable.Add(locale.DisplayLanguage);
					break;
				case LanguageAvailableResult.CountryAvailable:
					langAvailable.Add(locale.DisplayLanguage);
					break;
				case LanguageAvailableResult.CountryVarAvailable:
					langAvailable.Add(locale.DisplayLanguage);
					break;
				}

			}
			langAvailable = langAvailable.OrderBy(t => t).Distinct().ToList();

			var adapter = new ArrayAdapter<string>(this, Android.Resource.Layout.SimpleSpinnerDropDownItem, langAvailable);
			spinLanguages.Adapter = adapter;

			// set up the speech to use the default langauge
			// if a language is not available, then the default language is used.
			lang = Java.Util.Locale.Default;
			textToSpeech.SetLanguage(lang);

			// set the speed and pitch
			textToSpeech.SetPitch(.5f);
			textToSpeech.SetSpeechRate(.5f);

			// connect up the events
			btnSayIt.Click += delegate
			{
				// if there is nothing to say, don't say it
				if (!string.IsNullOrEmpty(editWhatToSay.Text))
					textToSpeech.Speak(editWhatToSay.Text, QueueMode.Flush, null);
			};

			// sliders
			seekPitch.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
			{
				var seek = sender as SeekBar;
				var progress = seek.Progress / 255f;
				textToSpeech.SetPitch(progress);
				txtPitchVal.Text = progress.ToString("F2");
			};
			seekSpeed.StopTrackingTouch += (object sender, SeekBar.StopTrackingTouchEventArgs e) =>
			{
				var seek = sender as SeekBar;
				var progress = seek.Progress / 255f;
				textToSpeech.SetSpeechRate(progress);
				txtSpeedVal.Text = progress.ToString("F2");
			};

			spinLanguages.ItemSelected += (object sender, AdapterView.ItemSelectedEventArgs e) =>
			{
				lang = Java.Util.Locale.GetAvailableLocales().FirstOrDefault(t => t.DisplayLanguage == langAvailable[(int)e.Id]);
				// create intent to check the TTS has this language installed
				var checkTTSIntent = new Intent();
				checkTTSIntent.SetAction(TextToSpeech.Engine.ActionCheckTtsData);
				StartActivityForResult(checkTTSIntent, NeedLang);
			};
		}
Exemplo n.º 11
0
        protected override void OnCreate(Bundle bundle)
        {
            base.OnCreate (bundle);

            SetContentView (Resource.Layout.Main);

            textToSpeak = FindViewById<EditText> (Resource.Id.textToSpeak);
            speechButton = FindViewById<Button> (Resource.Id.speechButton);
            speechItemListView = FindViewById<ListView> (Resource.Id.speechItemListView);

            speech = new TextToSpeech (this, this);
                        speech.SetLanguage (Java.Util.Locale.Default); //translate to default locale

            speechButton.Click += (object sender, EventArgs e) => {

                string text = textToSpeak.Text;

                if (!String.IsNullOrEmpty (text)) {
                    speech.Speak (text, QueueMode.Add, null);
                } else {
                                        Toast.MakeText (this, Resource.String.enter_text_to_speak, ToastLength.Short).Show ();
                }
            };

            speechItemListView.ChoiceMode = ChoiceMode.Single;

            if (speechItemListView != null) {
                speechItemListView.ItemClick += (object sender, AdapterView.ItemClickEventArgs e) => {
                    textToSpeak.Text = items [e.Position];
                    speechItemListView.SetSelection (e.Position);
                                        this.InvalidateOptionsMenu ();
                };
            }

                        textToSpeak.TextChanged += (sender, e) => this.InvalidateOptionsMenu();
        }
			protected override void OnActivityResult (int requestCode, Result resultCode, Intent data){
	    		base.OnActivityResult (requestCode, resultCode, data);
	        	if(requestCode == 100)
	        	{
	            	Speech = new TextToSpeech(this, this);
	            	Speech.SetLanguage(Java.Util.Locale.English);
	        	}
	        	else{
	        		Intent installIntent = new Intent();
            		installIntent.SetAction(TextToSpeech.Engine.ActionInstallTtsData);
            		StartActivity(installIntent);
	        	}
	    	}