Esempio n. 1
0
 void OnPrepared(Texture texture)
 {
     //Video size != Video buffer size (FramePixels has video buffer size), so we will use
     //previously created playback texture size that based on video buffer size
     _texture       = MediaPlayerHelper.GenVideoTexture(texture.width, texture.height);
     _image.texture = _texture;
 }
Esempio n. 2
0
    void Awake()
    {
        if (_videoImage != null)
        {
            if (MediaPlayerHelper.IsMobilePlatform())
            {
                _mediaPlayer = new MobileMediaPlayer(this, new[] { _videoImage.gameObject });
                _snapshot.gameObject.SetActive(false);
            }
            else
            {
                _mediaPlayer = new StandaloneMediaPlayer(this, new[] { _videoImage.gameObject });
            }

            // Auto clear texture after stop playback
            //_mediaPlayer.AutoClearVideoTexture = true;
            // Audio output of the video will be not muted
            _mediaPlayer.Mute = false;
            // Set default audio output volume
            _mediaPlayer.Volume = (int)_volume.value;
            // Attach scecial listeners to MediaPlayer instance
            AddListeners();
        }
        SetDebugVisibility(false);
    }
Esempio n. 3
0
    private void Awake()
    {
#if UNITY_EDITOR
        EditorApplication.playmodeStateChanged += HandleOnPlayModeChanged;
#endif

        if (_renderingObjects != null)
        {
            // Create instance of MediaPlayer object to specific platform with defined arguments
            if (MediaPlayerHelper.IsMobilePlatform())
            {
                _mediaPlayer = new MobileMediaPlayer(this, _renderingObjects, new DefinedArgs(null)
                {
                    FileCaching      = _fileCaching,
                    LiveCaching      = _liveCaching,
                    DiskCaching      = _diskCaching,
                    NetworkCaching   = _networkCaching,
                    HardwareDecoding = DefinedArgs.ArgsState.Default
                });
            }
            else
            {
                _mediaPlayer = new StandaloneMediaPlayer(this, _renderingObjects, new DefinedArgs(null)
                {
                    FileCaching      = _fileCaching,
                    LiveCaching      = _liveCaching,
                    DiskCaching      = _diskCaching,
                    NetworkCaching   = _networkCaching,
                    HardwareDecoding = DefinedArgs.ArgsState.Default,
                    //AudioOutputDevice = DefinedArgs.GetAudioOutputDevice("Rift Audio")
                });

#if UNITY_EDITOR
                _logManager = (_mediaPlayer as StandaloneMediaPlayer).LogManager;
                if (_logManager != null)
                {
                    // Set delegate for LogManager to show native library logging in Unity console
                    _logManager.LogMessageListener += UnityConsoleLogging;
                    // Set debugging level
                    _logManager.LogDetail = _consoleLogDetail;
                }
#endif
            }

            // Audio output of the video will be not muted
            _mediaPlayer.Mute = _mute;
            // Set audio output volume
            _mediaPlayer.Volume = _volume;
            // Create scpecial parser to add possibiity of get video link from different video hosting servies (like youtube)
            _videoHostingParser = new VideoHostingsParser(this);
            // Attach scecial listeners to MediaPlayer instance
            AddListeners();
        }
    }
Esempio n. 4
0
    void OnImageReady(Texture image)
    {
        _image.texture = image;

        if (_texture != null)
        {
            Destroy(_texture);
        }

        //Video size != Video buffer size (FramePixels has video buffer size), so we will use
        //previously created playback texture size that based on video buffer size
        _texture = MediaPlayerHelper.GenVideoTexture(image.width, image.height);
        //_image.texture = _texture;
        _texture.Apply();
    }
Esempio n. 5
0
        public void setTest()
        {
            if (sentences.Count == 0)
            {
                return;
            }
            EngGrid.Children.Clear();
            var nowSentence = sentences[nowIndex];

            string[] sentanceWords = nowSentence.Eng.Split(new char[] { ' ' });
            EngGrid.Visibility = Visibility.Hidden;
            ChiLB.Visibility   = Visibility.Hidden;
            #region 創建例句內所有單字按紐
            for (int j = 0; j < sentanceWords.Length; j++)
            {
                var column = new ColumnDefinition();
                EngGrid.ColumnDefinitions.Add(column);
                EngGrid.ColumnDefinitions[j].Width = GridLength.Auto;//給予grid寬度自動,防止按鈕部分遮蓋
                var button = new Button();
                button.Content = sentanceWords[j] + " ";
                button.HorizontalContentAlignment = HorizontalAlignment.Left;
                button.BorderThickness            = new Thickness(0);//按鈕框線粗細,0=看不到框線
                button.Background = Brushes.Black;
                button.Foreground = Brushes.Pink;
                button.FontSize   = 50;
                button.Click     += Button_Click;
                Grid.SetColumn(button, j);
                EngGrid.Children.Add(button);
            }
            #endregion
            ChiLB.Content = nowSentence.Chi;
            NormalPlayer  = new MediaPlayerHelper($"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q={nowSentence.Eng}");
            SlowPlayer    = new MediaPlayerHelper($"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&ttsspeed=0.1&q={nowSentence.Eng}");
            if ((bool)SlowVoiceCheckBox.IsChecked)
            {
                SlowPlayer.Play();
            }
            else
            {
                NormalPlayer.Play();
            }
        }
        public TrimmerViewModel(IVideoLibrary videoLibrary, INavigationService navigationService,
                                MediaPlayerService playerService, IFFmpegConverter fFmpegConverter)
        {
            App.DebugLog("");
            this.videoLibrary      = videoLibrary;
            this.navigationService = navigationService;
            this.playerService     = playerService;
            this.fFmpegConverter   = fFmpegConverter;
            fFmpegConverter.ConversionProgressChanged += FFmpegConverter_ProgressChanged;
            fFmpegConverter.ConversionStarted         += FFmpegConverter_ConversionStarted;
            fFmpegConverter.ConversionEnded           += FFmpegConverter_ConversionEnded;

            MediaHelper = new MediaPlayerHelper(playerService);
            MediaHelper.IsPausedByUser        = true;
            MediaHelper.MediaPlayerReady     += MediaPlayerHelper_MediaPlayerReady;
            MediaHelper.PlaybackStateChanged += MediaHelper_PlaybackStateChanged;

            GoToNextFavSceneCommand  = new DelegateCommand(GoToNextFavScene);
            GoToPrevFavSceneCommand  = new DelegateCommand(GoToPrevFavScene);
            IncrementPositionCommand = new DelegateCommand <object>((e) => IncrementPosition(e));
            DecrementPositionCommand = new DelegateCommand <object>((e) => DecrementPosition(e));
            JumpToStartCommand       = new DelegateCommand(() => JumpToStart());
            TogglePlayPauseCommand   = new DelegateCommand(TogglePlayPause);

            OffsetOptions = new ObservableCollection <OffsetOption>()
            {
                new OffsetOption("1 sec", TimeSpan.FromSeconds(1)),
                new OffsetOption("10 sec", TimeSpan.FromSeconds(10)),
                new OffsetOption("1 min", TimeSpan.FromMinutes(1)),
                new OffsetOption("10 min", TimeSpan.FromMinutes(10)),
            };
            SelectedOffsetOption = OffsetOptions.First();

            EndPosition   = TimeSpan.FromMinutes(1);
            TotalDuration = EndPosition;
        }
Esempio n. 7
0
    public static void UMPGUI()
    {
        if (!_preloaded)
        {
            _preloadedSettings = PreloadedSettings.Instance;
            _preloaded         = true;
        }

        _preloadedSettings.UseExternalLibs = EditorGUILayout.Toggle(new GUIContent("Use installed VLC libraries", "Will be using external/installed VLC player libraries for all UMP instances (global). Path to install VLC directory will be automatically obtained, but you can also setup your custom path."), _preloadedSettings.UseExternalLibs);

        var chachedLabelColor = EditorStyles.label.normal.textColor;

        EditorStyles.label.wordWrap         = true;
        EditorStyles.label.normal.textColor = Color.red;

        if (MediaPlayerHelper.GetLibsPath(false).Equals(string.Empty))
        {
            EditorGUILayout.LabelField("Please correctly import UMP (Win, Mac, Linux) package to use internal VLC libraries.");
            _preloadedSettings.UseExternalLibs = true;
        }

        EditorGUILayout.Space();

        if (_preloadedSettings.UseExternalLibs)
        {
            string externalLibsPath = MediaPlayerHelper.GetLibsPath(true);
            if (externalLibsPath.Equals(string.Empty))
            {
                EditorGUILayout.LabelField("Did you install VLC player software correctly? Please make sure that:");
                EditorGUILayout.LabelField("1. Your installed VLC player bit application == Unity Editor bit application (VLC player 64-bit == Unity 64-bit Editor);");
                EditorGUILayout.LabelField("2. Use last version installer from official site: ");

                var link = "https://www.videolan.org/vlc/index.ru.html";
                EditorStyles.label.normal.textColor = Color.blue;
                EditorGUILayout.LabelField(link);

                Rect linkRect = GUILayoutUtility.GetLastRect();

                if (Event.current.type == EventType.MouseUp && linkRect.Contains(Event.current.mousePosition))
                {
                    Application.OpenURL(link);
                }

                EditorStyles.label.normal.textColor = Color.red;
                EditorGUILayout.LabelField("Or you can try to use custom additional path to your VLC libraries.");

                EditorGUILayout.Space();
            }

            EditorStyles.label.normal.textColor = chachedLabelColor;

            EditorGUILayout.LabelField(new GUIContent("External/installed VLC libraries path:", "Default path to installed VLC player libraries. Example: '" + @"C:\Program Files\VideoLAN\VLC'."));
            GUIStyle pathLabel = EditorStyles.textField;
            pathLabel.wordWrap = true;
            EditorGUILayout.LabelField(externalLibsPath, pathLabel);

            EditorGUILayout.Space();

            EditorGUILayout.LabelField(new GUIContent("Additional external/installed VLC libraries path:", "Additional path to installed VLC player libraries. Will be used if path to libraries can't be automatically obtained. Example: '" + @"C:\Program Files\VideoLAN\VLC'."));
            GUIStyle additionalLabel = EditorStyles.textField;
            additionalLabel.wordWrap = true;

            _preloadedSettings.AdditionalLibsPath = EditorGUILayout.TextField(_additionalLibsPath, _preloadedSettings.AdditionalLibsPath);
        }

        EditorStyles.label.normal.textColor = chachedLabelColor;

        EditorGUILayout.Space();
        _preloadedSettings.UseAndroidNative = EditorGUILayout.Toggle(new GUIContent("Use Android native player", "Will be using Android native media player for all UMP instances (global)."), _preloadedSettings.UseAndroidNative);

        if (GUI.changed)
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
Esempio n. 8
0
    private IEnumerator VideoPathPreparing(string path, bool playImmediately, IPathPreparedListener listener)
    {
        if (_cachedVideoPaths.ContainsKey(path))
        {
            listener.OnPathPrepared(_cachedVideoPaths[path], playImmediately);
            yield break;
        }

#if UNITY_EDITOR
        _lastEventMsg = "Path Preparing";
#endif

        if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Android)
        {
            /// Check if we try to play exported videos and wait when export process will be completed
            var exptPaths = UMPSettings.GetSettings().AndroidExportedPaths;
            var filePath  = path.Replace("file:///", "");

            foreach (var exptPath in exptPaths)
            {
                if (exptPath.Contains(filePath))
                {
                    while (!_isExportCompleted)
                    {
                        yield return(null);
                    }

                    if (_cachedVideoPaths.ContainsKey(filePath))
                    {
                        listener.OnPathPrepared(_cachedVideoPaths[filePath], playImmediately);
                        yield break;
                    }

                    break;
                }
            }

            if ((_mediaPlayer.Options as PlayerOptionsAndroid).PlayerType ==
                PlayerOptionsAndroid.PlayerTypes.LibVLC &&
                MediaPlayerHelper.IsAssetsFile(path))
            {
                var tempFilePath = System.IO.Path.Combine(Application.temporaryCachePath, filePath);
                if (File.Exists(tempFilePath))
                {
                    _cachedVideoPaths.Add(path, tempFilePath);
                    listener.OnPathPrepared(tempFilePath, playImmediately);
                    yield break;
                }

                var www = new WWW(System.IO.Path.Combine(Application.streamingAssetsPath, filePath));
                yield return(www);

                if (string.IsNullOrEmpty(www.error))
                {
                    var tempFile = new FileInfo(tempFilePath);
                    tempFile.Directory.Create();
                    File.WriteAllBytes(tempFile.FullName, www.bytes);
                    _cachedVideoPaths.Add(path, tempFilePath);
                    path = tempFilePath;
                }
                else
                {
                    Debug.LogError("Can't create temp file from asset folder: " + www.error);
                }
                www.Dispose();
            }
        }

        if (_videoHostingParser.IsVideoHostingUrl(path))
        {
            var videoInfos = _videoHostingParser.GetCachedVideoInfos(path);

            if (videoInfos == null)
            {
                var isError = false;
                _isParsing = true;

                _videoHostingParser.ParseVideoInfos(path, (res) =>
                {
                    _isParsing = false;
                }, (error) =>
                {
                    isError = true;
                    Debug.LogError(error);
                });

                while (_isParsing)
                {
                    if (isError)
                    {
                        _isParsing = false;
                        yield break;
                    }

                    yield return(null);
                }

                videoInfos = _videoHostingParser.GetCachedVideoInfos(path);
            }

            var videoInfo  = _videoHostingParser.GetBestCompatibleVideo(videoInfos);
            var directLink = videoInfo.DownloadUrl;

            if (videoInfo.RequiresDecryption && !videoInfo.IsDecrypted)
            {
                var isDecrypted = false;
                _videoHostingParser.DecryptVideoUrl(videoInfo, (res) =>
                {
                    directLink  = videoInfo.DownloadUrl;
                    isDecrypted = true;
                });

                while (!isDecrypted)
                {
                    yield return(null);
                }
            }
            _cachedVideoPaths.Add(path, directLink);
            path = directLink;
        }

        listener.OnPathPrepared(path, playImmediately);
        yield return(null);
    }
    public static void UMPGUI()
    {
        if (!_preloaded)
        {
            _preloadedSettings = PreloadedSettings.Instance;
            _preloaded         = true;
        }

        EditorGUILayout.LabelField("Editor/Desktop platforms:", EditorStyles.boldLabel);

        EditorGUILayout.Space();

        _preloadedSettings.UseAudioSource = EditorGUILayout.Toggle(new GUIContent("Use Unity 'Audio Source' component", "Will be using Unity 'Audio Source' component for audio output for all UMP instances (global) by default."), _preloadedSettings.UseAudioSource);

        EditorGUILayout.Space();

        _preloadedSettings.UseDebugMode = EditorGUILayout.Toggle(new GUIContent("Debug mode", "Allows you to use debug mode in your IDE with UMP asset in Unity Editor (it's still experimental and will work only in Unity Editor, also some default UMP functions will not work in this mode, because it's conflicting with IDE debug mode)."), _preloadedSettings.UseDebugMode);

        EditorGUILayout.Space();

        _preloadedSettings.UseExternalLibs = EditorGUILayout.Toggle(new GUIContent("Use installed VLC libraries", "Will be using external/installed VLC player libraries for all UMP instances (global). Path to install VLC directory will be obtained automatically (you can also setup your custom path)."), _preloadedSettings.UseExternalLibs);

        var chachedLabelColor = EditorStyles.label.normal.textColor;

        EditorStyles.label.wordWrap         = true;
        EditorStyles.label.normal.textColor = Color.red;

        if (MediaPlayerHelper.GetLibsPath(false).Equals(string.Empty))
        {
            EditorGUILayout.LabelField("Please correctly import UMP (Win, Mac, Linux) package to use internal VLC libraries.");
            _preloadedSettings.UseExternalLibs = true;
        }

        EditorGUILayout.Space();

        if (_preloadedSettings.UseExternalLibs)
        {
            string externalLibsPath = MediaPlayerHelper.GetLibsPath(true);
            if (externalLibsPath.Equals(string.Empty))
            {
                EditorGUILayout.LabelField("Did you install VLC player software correctly? Please make sure that:");
                EditorGUILayout.LabelField("1. Your installed VLC player bit application == Unity Editor bit application (VLC player 64-bit == Unity 64-bit Editor);");
                EditorGUILayout.LabelField("2. Use last version installer from official site: ");

                var link = "https://www.videolan.org/vlc/index.ru.html";
                EditorStyles.label.normal.textColor = Color.blue;
                EditorGUILayout.LabelField(link);

                Rect linkRect = GUILayoutUtility.GetLastRect();

                if (Event.current.type == EventType.MouseUp && linkRect.Contains(Event.current.mousePosition))
                {
                    Application.OpenURL(link);
                }

                EditorStyles.label.normal.textColor = Color.red;
                EditorGUILayout.LabelField("Or you can try to use custom additional path to your VLC libraries.");

                EditorGUILayout.Space();
            }

            EditorStyles.label.normal.textColor = chachedLabelColor;

            EditorGUILayout.LabelField(new GUIContent("External/installed VLC libraries path:", "Default path to installed VLC player libraries. Example: '" + @"C:\Program Files\VideoLAN\VLC'."));
            GUIStyle pathLabel = EditorStyles.textField;
            pathLabel.wordWrap = true;
            EditorGUILayout.LabelField(externalLibsPath, pathLabel);

            EditorGUILayout.Space();

            EditorGUILayout.LabelField(new GUIContent("Additional external/installed VLC libraries path:", "Additional path to installed VLC player libraries. Will be used if path to libraries can't be automatically obtained. Example: '" + @"C:\Program Files\VideoLAN\VLC'."));
            GUIStyle additionalLabel = EditorStyles.textField;
            additionalLabel.wordWrap = true;

            _preloadedSettings.AdditionalLibsPath = EditorGUILayout.TextField(_additionalLibsPath, _preloadedSettings.AdditionalLibsPath);
        }

        EditorStyles.label.normal.textColor = chachedLabelColor;

        EditorGUILayout.Space();

        EditorGUILayout.LabelField("Mobile platforms:", EditorStyles.boldLabel);

        EditorGUILayout.Space();

        _preloadedSettings.UseAndroidNative = EditorGUILayout.Toggle(new GUIContent("Use Android native player", "Will be using Android native media player for all UMP instances (global)."), _preloadedSettings.UseAndroidNative);

        if (_nativeLibraryPrepare != _preloadedSettings.UseAndroidNative)
        {
            List <string> libs = new List <string>();
            libs.AddRange(Directory.GetFiles(Application.dataPath + "/UniversalMediaPlayer/Plugins/Android/libs/armeabi-v7a"));
            libs.AddRange(Directory.GetFiles(Application.dataPath + "/UniversalMediaPlayer/Plugins/Android/libs/x86"));

            foreach (var lib in libs)
            {
                if (lib.Contains(".meta") && !lib.Contains("libUniversalMediaPlayer"))
                {
                    File.SetAttributes(lib, FileAttributes.Normal);
                    string metaData = File.ReadAllText(lib);
                    var    match    = Regex.Match(metaData, @"Android.*\s*enabled:.");

                    if (match.Success)
                    {
                        metaData = Regex.Replace(metaData, @"Android.*\s*enabled:." + (!_nativeLibraryPrepare ? 1 : 0), match.Value + (_nativeLibraryPrepare ? 1 : 0));
                        File.WriteAllText(lib, metaData);
                    }
                }
            }
            libs.Clear();
        }

        _nativeLibraryPrepare = _preloadedSettings.UseAndroidNative;

        if (GUI.changed)
        {
            AssetDatabase.SaveAssets();
            AssetDatabase.Refresh();
        }
    }
        public PreviewAudioHost()
        {
            this.InitializeComponent();

            m_mediaPlayerHelper = new MediaPlayerHelper(MediaElementAudio);
        }
Esempio n. 11
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 = "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.Low ||
                args.Result.Confidence == SpeechRecognitionConfidence.Medium ||
                args.Result.Confidence == SpeechRecognitionConfidence.High)
            {
                await dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() =>
                {
                    heardYouSayTextBlock.Visibility = Visibility.Visible;
                    resultTextBlock.Visibility      = Visibility.Visible;
                    resultTextBlock.Text            = string.Format("Heard: '{0}', (Tag: '{1}', Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
                    switch (tag)
                    {
                    case TagCommands.GetJoke:
                        {
                            var res = await JokeHelper.GetJoke();
                            if (!string.IsNullOrEmpty(res.value.joke))
                            {
                                await speech.Read(res.value.joke);
                                resultTextBlock.Text = res.value.joke;
                            }
                        }
                        break;

                    case TagCommands.HowOld:
                        {
                            var photo = await TakePhoto();
                            //call computer vision
                            var faces = await ApiContainer.GetApi <FaceService>().UploadAndDetectFaceAttributes(photo);
                            var res   = ApiContainer.GetApi <FaceService>().HowOld(faces);
                            if (!string.IsNullOrEmpty(res))
                            {
                                await speech.Read(res);
                                resultTextBlock.Text = res;
                            }
                        }
                        break;

                    case TagCommands.Calling:
                        await speech.Read("Yes, what can I do Boss?");
                        break;

                    case TagCommands.SeeMe:
                        {
                            var photo = await TakePhoto();
                            //call computer vision
                            var res = await ApiContainer.GetApi <ComputerVisionService>().RecognizeImage(photo);
                            if (!string.IsNullOrEmpty(res))
                            {
                                await speech.Read(res);
                                resultTextBlock.Text = "I see " + res;
                            }
                        }
                        break;

                    case TagCommands.ReadText:
                        {
                            var photo = await TakePhoto();
                            //call computer vision
                            var res = await ApiContainer.GetApi <ComputerVisionService>().RecognizeText(photo);
                            if (!string.IsNullOrEmpty(res))
                            {
                                await speech.Read(res);
                                resultTextBlock.Text = "read: " + res;
                            }
                        }
                        break;

                    case TagCommands.Stop:
                        Player1.MediaPlayer.Pause();
                        break;

                    case TagCommands.PlayBlues:
                    case TagCommands.PlaySlow:
                    case TagCommands.PlayRock:
                    case TagCommands.PlayJazz:
                    case TagCommands.PlayElectro:

                        {
                            var genre = Genre.Slow;
                            switch (tag)
                            {
                            case TagCommands.PlayBlues: genre = Genre.Blues; break;

                            case TagCommands.PlayRock: genre = Genre.Rock; break;

                            case TagCommands.PlaySlow: genre = Genre.Slow; break;

                            case TagCommands.PlayJazz: genre = Genre.Jazz; break;

                            case TagCommands.PlayElectro: genre = Genre.Electro; break;
                            }
                            var rnd    = new Random(Environment.TickCount);
                            var selIds = SongIDs[genre];
                            var num    = rnd.Next(0, selIds.Length - 1);
                            var url    = await YouTube.GetVideoUriAsync(selIds[num], YouTubeQuality.QualityLow);
                            MediaPlayerHelper.CleanUpMediaPlayerSource(Player1.MediaPlayer);
                            Player1.MediaPlayer.Source = new MediaItem(url.Uri.ToString()).MediaPlaybackItem;
                            Player1.MediaPlayer.Play();
                        }

                        break;

                    case TagCommands.TakePhoto:
                        await speech.Read("I will take your picture boss");
                        //GetPhotoFromCam();
                        break;

                    case TagCommands.Thanks:
                        await speech.Read("My pleasure boss");
                        break;

                    case TagCommands.TurnOnLamp:
                        {
                            //await speech.Read("Turn on the light");
                            //var Pesan = Encoding.UTF8.GetBytes("LIGHT_ON");
                            //clientMqtt.PublishMessage(Pesan);
                        }
                        break;

                    case TagCommands.TurnOffLamp:
                        {
                            //await speech.Read("Turn off the light");
                            //var Pesan = Encoding.UTF8.GetBytes("LIGHT_OFF");
                            //clientMqtt.Publish( Pesan);
                        }
                        break;

                    case TagCommands.ReciteQuran:
                        {
                            try
                            {
                                Random rnd = new Random(Environment.TickCount);
                                var surah  = rnd.Next(1, 114);
                                var rslt   = await httpClient.GetAsync($"http://qurandataapi.azurewebsites.net/api/Ayah/GetAyahCountBySurah?Surah={surah}");
                                var ayah   = int.Parse(await rslt.Content.ReadAsStringAsync());
                                ayah       = rnd.Next(1, ayah);
                                rslt       = await httpClient.GetAsync($"http://qurandataapi.azurewebsites.net/api/Ayah/GetMediaByAyah?Surah={surah}&Ayah={ayah}&ReciterId=11");
                                var media  = JsonConvert.DeserializeObject <QuranMedia>(await rslt.Content.ReadAsStringAsync());
                                if (media != null)
                                {
                                    MediaPlayerHelper.CleanUpMediaPlayerSource(Player1.MediaPlayer);
                                    Player1.MediaPlayer.Source = new MediaItem(media.Url).MediaPlaybackItem;
                                    Player1.MediaPlayer.Play();
                                }
                            }
                            catch
                            {
                                await speech.Read("there is problem on the service");
                            }
                        }
                        break;

                    case TagCommands.WhatDate: { await speech.Read("Today is " + DateTime.Now.ToString("dd MMMM yyyy")); }; break;

                    case TagCommands.WhatTime: { await speech.Read("Current time is " + DateTime.Now.ToString("HH:mm")); }; break;

                    default:
                        for (int x = 0; x < Devices.Count; x++)
                        {
                            if (tag == $"TURNON{x}")
                            {
                                SwitchDevice(true, Devices[x].IP);
                                break;
                            }
                            else if (tag == $"TURNOFF{x}")
                            {
                                SwitchDevice(false, Devices[x].IP);
                                break;
                            }
                        }
                        break;
                    }
                });
            }
            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, () =>
                {
                    heardYouSayTextBlock.Visibility = Visibility.Collapsed;
                    resultTextBlock.Visibility      = Visibility.Visible;
                    resultTextBlock.Text            = string.Format("Sorry, I didn't catch that. (Heard: '{0}', Tag: {1}, Confidence: {2})", args.Result.Text, tag, args.Result.Confidence.ToString());
                });
            }
        }
Esempio n. 12
0
    public override void OnInspectorGUI()
    {
        serializedObject.Update();

        var umpEditor = (UniversalMediaPlayer)target;

        EditorGUIUtility.labelWidth = 0;
        EditorGUIUtility.fieldWidth = 0;

        EditorGUI.BeginChangeCheck();

        _savedFontStyle = EditorStyles.label.fontStyle;
        _savedTextColor = EditorStyles.textField.normal.textColor;

        #region Rendering Field
        EditorGUILayout.Space();
        EditorGUILayout.PropertyField(_renderingObjectsProp, new GUIContent("Rendering GameObjects:"), true);
        #endregion

        #region Audio Field
        EditorGUI.BeginDisabledGroup(Application.isPlaying);
        EditorGUILayout.Space();
        EditorGUILayout.PropertyField(_audioSourcesProp, new GUIContent("Audio Sources (only PC, Mac & Linux):"), true);
        EditorGUI.EndDisabledGroup();
        #endregion

        #region Path Field
        EditorGUILayout.Space();

        EditorStyles.label.fontStyle = FontStyle.Bold;
        EditorGUILayout.LabelField("Path to video file:");
        EditorStyles.label.fontStyle    = _savedFontStyle;
        EditorStyles.textField.wordWrap = true;
        _pathProp.stringValue           = EditorGUILayout.TextField(_pathProp.stringValue, GUILayout.Height(30));
        EditorStyles.textField.wordWrap = false;
        #endregion

        #region Additional Fields
        EditorGUILayout.Space();
        EditorStyles.label.fontStyle = FontStyle.Bold;
        EditorGUILayout.LabelField("Additional properties:");
        EditorStyles.label.fontStyle = _savedFontStyle;

        GUILayout.BeginVertical("Box");
        GUILayout.BeginHorizontal();
        AutoSizeLabelField("Auto play:");
        GUILayout.FlexibleSpace();
        _autoPlayProp.boolValue = EditorGUILayout.Toggle(_autoPlayProp.boolValue);
        AutoSizeLabelField("Loop:");
        GUILayout.FlexibleSpace();
        _loopProp.boolValue = EditorGUILayout.Toggle(_loopProp.boolValue);
        AutoSizeLabelField("Mute:");
        GUILayout.FlexibleSpace();
        _muteProp.boolValue = EditorGUILayout.Toggle(_muteProp.boolValue);
        GUILayout.EndHorizontal();

        GUILayout.BeginHorizontal();
        AutoSizeLabelField("Advanced:");
        _showAdvancedProperties.boolValue = EditorGUILayout.Toggle(_showAdvancedProperties.boolValue);
        GUILayout.EndHorizontal();

        if (_showAdvancedProperties.boolValue)
        {
            EditorStyles.label.normal.textColor = Color.black;
            EditorStyles.label.fontStyle        = FontStyle.Italic;
            EditorGUILayout.LabelField("Don't support on iOS/WebGL platforms", GUILayout.Width(240));
            EditorStyles.label.normal.textColor = _savedTextColor;
            EditorStyles.label.fontStyle        = _savedFontStyle;
            EditorGUILayout.Space();

            EditorGUI.BeginDisabledGroup(Application.isPlaying);

            float cachedLabelWidth = EditorGUIUtility.labelWidth;
            EditorGUIUtility.labelWidth = 170;
            _fileCachingProp.intValue   = EditorGUILayout.IntField("File caching (ms): ", _fileCachingProp.intValue);
            _fileCachingProp.intValue   = Mathf.Clamp(_fileCachingProp.intValue, 0, 60000);

            _liveCachingProp.intValue = EditorGUILayout.IntField("Live capture caching (ms): ", _liveCachingProp.intValue);
            _liveCachingProp.intValue = Mathf.Clamp(_liveCachingProp.intValue, 0, 60000);

            _diskCachingProp.intValue = EditorGUILayout.IntField("Disc caching (ms): ", _diskCachingProp.intValue);
            _diskCachingProp.intValue = Mathf.Clamp(_diskCachingProp.intValue, 0, 60000);

            _networkCachingProp.intValue = EditorGUILayout.IntField("Network caching (ms): ", _networkCachingProp.intValue);
            _networkCachingProp.intValue = Mathf.Clamp(_networkCachingProp.intValue, 0, 60000);

            EditorGUIUtility.labelWidth = cachedLabelWidth;

            EditorGUI.EndDisabledGroup();
        }
        else
        {
            _fileCachingProp.intValue    = PlayerArguments.ADVANCED_DEFAULT_CACHING;
            _liveCachingProp.intValue    = PlayerArguments.ADVANCED_DEFAULT_CACHING;
            _diskCachingProp.intValue    = PlayerArguments.ADVANCED_DEFAULT_CACHING;
            _networkCachingProp.intValue = PlayerArguments.ADVANCED_DEFAULT_CACHING;
        }

        if (PreloadedSettings.Instance.UseExternalLibs)
        {
            if (_externalPath.Equals(string.Empty))
            {
                _externalPath = MediaPlayerHelper.GetLibsPath(true);
            }

            if (_externalPath != string.Empty)
            {
                var wrapTextStyle = EditorStyles.textArea;
                wrapTextStyle.wordWrap = true;
                EditorGUILayout.LabelField("Path to external/installed libraries: '" + _externalPath + "'", wrapTextStyle);
            }
        }
        else
        {
            _externalPath = string.Empty;
        }

        GUILayout.EndVertical();
        #endregion

        #region Player Fields
        EditorGUILayout.Space();
        EditorStyles.label.fontStyle = FontStyle.Bold;
        EditorGUILayout.LabelField("Player properties:");
        EditorStyles.label.fontStyle = _savedFontStyle;
        GUILayout.BeginHorizontal();

        GUILayout.BeginVertical("Box");

        GUILayout.BeginHorizontal();
        var centeredStyle = GUI.skin.GetStyle("Label");
        centeredStyle.alignment = TextAnchor.MiddleCenter;
        EditorGUILayout.LabelField("Volume", centeredStyle, GUILayout.Width((Screen.width - 120) / 2f));
        if (GUILayout.Button("x", GUILayout.Width(15), GUILayout.Height(13)))
        {
            _volumeProp.intValue = 50;
        }
        GUILayout.EndHorizontal();

        _volumeProp.intValue = EditorGUILayout.IntSlider(_volumeProp.intValue, 0, 100);
        GUILayout.EndVertical();

        GUILayout.BeginVertical("Box");

        GUILayout.BeginHorizontal();
        EditorGUILayout.LabelField("Play rate", centeredStyle, GUILayout.Width((Screen.width - 120) / 2f));
        if (GUILayout.Button("x", GUILayout.Width(15), GUILayout.Height(13)))
        {
            _playRateProp.floatValue = 1f;
        }
        GUILayout.EndHorizontal();

        _playRateProp.floatValue = EditorGUILayout.Slider(_playRateProp.floatValue, 0.5f, 5f);
        GUILayout.EndVertical();

        GUILayout.EndHorizontal();

        EditorGUI.BeginDisabledGroup(!umpEditor.IsReady);
        EditorGUILayout.Space();
        GUILayout.BeginVertical("Box");
        EditorGUILayout.LabelField("Position", centeredStyle, GUILayout.ExpandWidth(true));
        _positionProp.floatValue = EditorGUILayout.Slider(_positionProp.floatValue, 0f, 1f);
        GUILayout.EndVertical();
        EditorGUI.EndDisabledGroup();

        EditorGUI.BeginDisabledGroup(!Application.isPlaying || !umpEditor.isActiveAndEnabled || umpEditor.IsParsing);
        GUILayout.BeginHorizontal("Box");
        if (GUILayout.Button("LOAD", GUILayout.Width(Screen.width / 6.5f)))
        {
            umpEditor.Prepare();
        }
        if (GUILayout.Button("PLAY", GUILayout.Width(Screen.width / 6.5f)))
        {
            umpEditor.Play();
        }
        if (GUILayout.Button("PAUSE", GUILayout.Width(Screen.width / 6.5f)))
        {
            umpEditor.Pause();
        }
        if (GUILayout.Button("STOP", GUILayout.Width(Screen.width / 6.5f)))
        {
            umpEditor.Stop();
        }
        if (GUILayout.Button("SHOT"))
        {
            umpEditor.Snapshot(Application.persistentDataPath);
        }
        GUILayout.EndHorizontal();
        EditorGUI.EndDisabledGroup();
        #endregion

        #region Events & Logging Fields
        EditorGUILayout.Space();
        EditorStyles.label.fontStyle = FontStyle.Bold;
        EditorGUILayout.LabelField("Events & Logging:", GUILayout.Width(150));
        EditorStyles.label.fontStyle = _savedFontStyle;

        if (Application.platform == RuntimePlatform.WindowsEditor || Application.platform == RuntimePlatform.OSXEditor)
        {
            GUILayout.BeginVertical("Box");
            EditorGUILayout.PropertyField(_logDetailProp);

            GUILayout.BeginHorizontal();
            AutoSizeLabelField("Last msg: ");
            _lastMsgScrollPos = GUILayout.BeginScrollView(_lastMsgScrollPos, GUILayout.Height(35));
            EditorStyles.label.normal.textColor = Color.black;
            EditorStyles.label.fontStyle        = FontStyle.Italic;
            EditorGUILayout.LabelField(_lastEventMsgProp.stringValue);
            EditorStyles.label.normal.textColor = _savedTextColor;
            EditorStyles.label.fontStyle        = _savedFontStyle;
            GUILayout.EndScrollView();
            GUILayout.EndHorizontal();
            GUILayout.EndVertical();
        }
        else
        {
            GUILayout.BeginVertical("Box");
            EditorGUILayout.LabelField("Not yet supported on this platform");
            GUILayout.EndVertical();
        }

        _showEventsListeners = EditorGUILayout.Foldout(_showEventsListeners, "Event Listeners");

        if (_showEventsListeners)
        {
            EditorGUILayout.PropertyField(_openingEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_bufferingEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_playingEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_pausedEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_stoppedEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_endReachedEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_encounteredErrorEventProp, true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_timeChangedEventProp, new GUIContent("Time Changed"), true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_positionChangedEventProp, new GUIContent("Position Changed"), true, GUILayout.Width(Screen.width - _barWidth));
            EditorGUILayout.PropertyField(_snapshotTakenEventProp, new GUIContent("Snapshot"), true, GUILayout.Width(Screen.width - _barWidth));
        }
        #endregion

        //EditorGUILayout.EndScrollView();
        Repaint();

        EditorStyles.label.normal.textColor = _savedTextColor;
        EditorStyles.label.fontStyle        = _savedFontStyle;

        if (EditorGUI.EndChangeCheck())
        {
            serializedObject.ApplyModifiedProperties();
        }
    }
    private IEnumerator VideoPathPreparing(string path, bool playImmediately, IPathPreparedListener listener)
    {
        if (_cachedVideoPaths.ContainsKey(path))
        {
            listener.OnPathPrepared(_cachedVideoPaths[path], playImmediately);
            yield break;
        }

#if UNITY_EDITOR
        _lastEventMsg = "Path Preparing";
#endif

        if (UMPSettings.SupportedPlatform == UMPSettings.Platforms.Android &&
            !UMPSettings.Instance.UseAndroidNative &&
            MediaPlayerHelper.IsAssetsFile(path))
        {
            var filePath     = path.Replace("file:///", "");
            var tempFilePath = System.IO.Path.Combine(Application.temporaryCachePath, filePath);
            if (File.Exists(tempFilePath))
            {
                _cachedVideoPaths.Add(path, tempFilePath);
                listener.OnPathPrepared(tempFilePath, playImmediately);
                yield break;
            }

            var www = new WWW(System.IO.Path.Combine(Application.streamingAssetsPath, filePath));
            yield return(www);

            if (string.IsNullOrEmpty(www.error))
            {
                File.WriteAllBytes(tempFilePath, www.bytes);
                _cachedVideoPaths.Add(path, tempFilePath);
                path = tempFilePath;
            }
            else
            {
                Debug.LogError("Can't create temp file from asset folder: " + www.error);
            }
            www.Dispose();
        }

        if (_videoHostingParser.IsVideoHostingUrl(path))
        {
            var videoInfos = _videoHostingParser.GetCachedVideoInfos(path);

            if (videoInfos == null)
            {
                var isError = false;
                _isParsing = true;

                _videoHostingParser.ParseVideoInfos(path, (res) =>
                {
                    _isParsing = false;
                }, (error) =>
                {
                    isError = true;
                    Debug.LogError(error);
                });

                while (_isParsing)
                {
                    if (isError)
                    {
                        _isParsing = false;
                        yield break;
                    }

                    yield return(null);
                }

                videoInfos = _videoHostingParser.GetCachedVideoInfos(path);
            }

            var videoInfo  = _videoHostingParser.GetBestCompatibleVideo(videoInfos);
            var directLink = videoInfo.DownloadUrl;

            if (videoInfo.RequiresDecryption && !videoInfo.IsDecrypted)
            {
                var isDecrypted = false;
                _videoHostingParser.DecryptVideoUrl(videoInfo, (res) =>
                {
                    directLink  = videoInfo.DownloadUrl;
                    isDecrypted = true;
                });

                while (!isDecrypted)
                {
                    yield return(null);
                }
            }
            _cachedVideoPaths.Add(path, directLink);
            path = directLink;
        }

        listener.OnPathPrepared(path, playImmediately);
        yield return(null);
    }
        /// <summary>設置題目,包含控制項改動</summary>
        private void setTest()
        {
            NormalPlayer.Clear();
            SlowPlayer.Clear();

            string wordstr = GetRandomWord();

            if (wordstr != "沒單字")
            {
                wordLabel.Content = wordstr;
                var word = LocalData.Words[wordstr];

                //設題目時先載入音檔,避免每次播放都要載入。
                GooglePlayer                = new MediaPlayerHelper($"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q={wordstr}");
                VoiceTubePlayer             = new MediaPlayerHelper($"https://tw.voicetube.com/player/{wordstr}.mp3");
                phoneticSymbolLabel.Content = word.phoneticSymbol; //show音標
                ChiTextBlock.Text           = "";
                foreach (var s in word.chineseMeaning)             //show詞性、中文意思
                {
                    ChiTextBlock.Text += $"{s.Key}\n";
                    for (int i = 0; i < s.Value.Count; i++)
                    {
                        ChiTextBlock.Text += $"  {s.Value[i]}\n";
                    }
                }
                for (int i = 0; i < LocalData.Sentances[wordstr].Count; i++)
                {
                    //載入例句音檔
                    NormalPlayer.Add(new MediaPlayerHelper($"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&q={LocalData.Sentances[wordstr][i].Eng}"));
                    SlowPlayer.Add(new MediaPlayerHelper($"https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=en&ttsspeed=0.1&q={LocalData.Sentances[wordstr][i].Eng}"));
                    //新增英文和中文的Row
                    SentenceGrid.RowDefinitions.Add(new RowDefinition());
                    SentenceGrid.RowDefinitions.Add(new RowDefinition());
                    var grid  = new Grid();
                    var label = new Label();
                    label.Content    = LocalData.Sentances[wordstr][i].Chi;
                    label.Visibility = Visibility.Hidden;
                    label.Foreground = Brushes.Gainsboro;
                    label.FontSize   = 45;
                    string[] sentanceWords = LocalData.Sentances[wordstr][i].Eng.Split(new char[] { ' ' });
                    grid.HorizontalAlignment = HorizontalAlignment.Left;
                    grid.Visibility          = Visibility.Hidden;
                    #region 創建例句內所有單字按紐
                    for (int j = 0; j < sentanceWords.Length; j++)
                    {
                        var column = new ColumnDefinition();
                        grid.ColumnDefinitions.Add(column);
                        grid.ColumnDefinitions[j].Width = GridLength.Auto;//給予grid寬度自動,防止按鈕部分遮蓋
                        var button = new Button();
                        button.Content = sentanceWords[j] + " ";
                        button.HorizontalContentAlignment = HorizontalAlignment.Left;
                        button.BorderThickness            = new Thickness(0);//按鈕框線粗細,0=看不到框線
                        button.Background = Brushes.Black;
                        button.Foreground = Brushes.Pink;
                        button.FontSize   = 45;
                        button.Click     += Button_Click;
                        Grid.SetColumn(button, j);
                        grid.Children.Add(button);
                    }
                    #endregion
                    #region 創建例句播放聲音按紐
                    var column2 = new ColumnDefinition();
                    grid.ColumnDefinitions.Add(column2);
                    var sentanceVoiceButton = new Button();
                    sentanceVoiceButton.Content           = $"_{i}Play";
                    sentanceVoiceButton.FontSize          = 45;
                    sentanceVoiceButton.Tag               = i;
                    sentanceVoiceButton.VerticalAlignment = VerticalAlignment.Center;
                    sentanceVoiceButton.Click            += SentanceVoiceButton_Click;
                    Grid.SetColumn(sentanceVoiceButton, sentanceWords.Length);
                    grid.Children.Add(sentanceVoiceButton);
                    #endregion
                    Grid.SetRow(grid, i * 2);
                    Grid.SetRow(label, i * 2 + 1);
                    SentenceGrid.Children.Add(grid);
                    SentenceGrid.Children.Add(label);
                }
            }
            else//沒有不熟單字的情況
            {
                ruleLabel1.Content   = "目前沒有不熟的單字";
                ruleLabel2.Content   = "請先去新增單字";
                NextButton.IsEnabled = false;
            }
        }