如何监听MediaPlayerElement的TimedTextSource变更事件?
Hey there! I’ve spent a fair amount of time working with MediaPlayerElement in UWP, so I can walk you through how to detect when a TimedTextSource changes—since there’s no out-of-the-box event for this, we’ll use a couple of reliable workarounds:
Option 1: Create a wrapped property with a custom event
If you’re setting the TimedTextSource directly in your code, you can wrap it in a property that triggers a custom event whenever the value updates. This gives you full control over when the change is detected:private TimedTextSource _activeTimedTextSource; public TimedTextSource ActiveTimedTextSource { get => _activeTimedTextSource; set { if (_activeTimedTextSource != value) { _activeTimedTextSource = value; // Raise your custom change event TimedTextSourceChanged?.Invoke(this, EventArgs.Empty); } } } // Define the custom event to subscribe to public event EventHandler TimedTextSourceChanged;Then, whenever you assign
ActiveTimedTextSource = newTimedSource, you can listen toTimedTextSourceChangedto run your logic.Option 2: Monitor MediaSource’s ExternalTimedTextSources collection
If your TimedTextSource is added to aMediaSourceviaExternalTimedTextSources, this collection is anObservableCollection—so you can listen to itsCollectionChangedevent to detect when sources are added or removed:// Assume you have a MediaSource set up for your media var mediaSource = MediaSource.CreateFromUri(new Uri("your-media-file-path-or-url")); // Subscribe to the collection change event mediaSource.ExternalTimedTextSources.CollectionChanged += (sender, e) => { switch (e.Action) { case NotifyCollectionChangedAction.Add: foreach (var item in e.NewItems) { if (item is TimedTextSource newSource) { // Handle new TimedTextSource being added } } break; case NotifyCollectionChangedAction.Remove: // Handle TimedTextSource being removed break; } }; // Assign the MediaSource to your MediaPlayerElement mediaPlayerElement.Source = MediaPlaybackItem.CreateFromMediaSource(mediaSource);Bonus: Track subtitle track changes
If you need to react when the user switches between subtitle tracks (which are part of a TimedTextSource), you can listen to theMediaPlayer.TimedMetadataTracksChangedevent:mediaPlayerElement.MediaPlayer.TimedMetadataTracksChanged += (sender, e) => { // Check which track is now active and respond accordingly var activeTrack = mediaPlayerElement.MediaPlayer.TimedMetadataTracks.FirstOrDefault(t => t.IsActive); if (activeTrack != null) { // Do something with the active subtitle track } };
The reason there’s no built-in TimedTextSourceChanged event is that the framework expects developers to handle source assignment logic directly, or use the MediaSource collection events for dynamic updates. These workarounds cover most use cases you’ll run into!
内容的提问来源于stack exchange,提问作者Vincent

