public void SetOverlayData(GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties) { lblTitle.Content = mediaProperties.Title; lblArtist.Content = mediaProperties.Artist + " • " + mediaProperties.AlbumTitle; imgAlbum.Source = CropBitmapImage(MediaControl.GetBitmapImageFromStream(mediaProperties.Thumbnail)); imgAlbum.Stretch = Stretch.UniformToFill; }
public static void Reload() { if (_smtcManager != null) { _smtcManager.CurrentSessionChanged -= SmtcManagerOnCurrentSessionChanged; _smtcManager.SessionsChanged -= SmtcManagerOnSessionsChanged; } if (_smtc != null) { _smtc.MediaPropertiesChanged -= SmtcOnMediaPropertiesChanged; _smtc.TimelinePropertiesChanged -= SmtcOnTimelinePropertiesChanged; } //TODO: Implement automatic switching to new playing smtc _smtcManager = GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult(); _smtcManager.SessionsChanged += SmtcManagerOnSessionsChanged; _smtcManager.CurrentSessionChanged += SmtcManagerOnCurrentSessionChanged; _smtc = _smtcManager.GetCurrentSession(); if (_smtc != null) { _smtc.MediaPropertiesChanged += SmtcOnMediaPropertiesChanged; _smtc.TimelinePropertiesChanged += SmtcOnTimelinePropertiesChanged; _mediaProperties = _smtc.TryGetMediaPropertiesAsync().GetAwaiter().GetResult(); UpdateMediaProperties(); } }
private async void Session_MediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args) { properties = await session.TryGetMediaPropertiesAsync(); string status = "[MediaPropertiesChanged] Artist: " + properties.Artist + ", Title: " + properties.Title; Debug.WriteLine(status); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { Status.Text = status; }); }
private void MediaManager_OnSongChanged(MediaManager.MediaSession sender, GlobalSystemMediaTransportControlsSessionMediaProperties args) { textBox2.Text = args.Title; textBox3.Text = args.Artist; if (args.Thumbnail != null) { //Task<Image> ti = GetImage(args.Thumbnail); //ti.Wait(); label5.Image = GetImage(args.Thumbnail); } }
public TrackInfo GetTrackInfo() { var result = new TrackInfo(); GlobalSystemMediaTransportControlsSessionMediaProperties currentTrack = null; currentTrack = GlobalSystemMediaTransportControlsSessionManager.RequestAsync().GetAwaiter().GetResult().GetCurrentSession().TryGetMediaPropertiesAsync().GetAwaiter().GetResult(); result.Title = currentTrack.Title ?? "Unknown Title"; result.Artist = currentTrack.Artist ?? currentTrack.AlbumArtist ?? "Unknown Artist"; result.Album = currentTrack.AlbumTitle ?? currentTrack.AlbumTitle; return(result); }
//TODO: this does not trigger private static void SmtcManagerOnCurrentSessionChanged(GlobalSystemMediaTransportControlsSessionManager sender, CurrentSessionChangedEventArgs args) { if (_smtc != null) { _smtc.MediaPropertiesChanged -= SmtcOnMediaPropertiesChanged; _smtc.TimelinePropertiesChanged -= SmtcOnTimelinePropertiesChanged; } _smtc = sender.GetCurrentSession(); if (_smtc != null) { _smtc.MediaPropertiesChanged += SmtcOnMediaPropertiesChanged; _mediaProperties = _smtc.TryGetMediaPropertiesAsync().GetAwaiter().GetResult(); } }
static string PrintMediaProperties(GlobalSystemMediaTransportControlsSessionMediaProperties props, string videoSymbol, string musicSymbol) { if (props.PlaybackType.HasValue) { switch (props.PlaybackType.Value) { case MediaPlaybackType.Music: return($"{musicSymbol} {props.Title} by {props.Artist}"); case MediaPlaybackType.Video: return($"{videoSymbol} {props.Title}"); } } return(""); }
private async Task <JObject> GetInfo() { var sessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync(); var currentSession = sessionManager.GetCurrentSession(); GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = null; byte[] bytes = null; if (currentSession == null) { _logger.Debug("Nothing is playing!"); } else { mediaProperties = await currentSession.TryGetMediaPropertiesAsync(); var previewStream = await mediaProperties.Thumbnail.OpenReadAsync(); bytes = new byte[previewStream.Size]; await previewStream.AsStream().ReadAsync(bytes, 0, (int)previewStream.Size); } var volume = await _defaultAudioDevice.GetVolumeAsync(); var resultObj = new JObject { ["success"] = true, ["title"] = mediaProperties?.Title, ["volume"] = volume, ["muted"] = _defaultAudioDevice.IsMuted, ["preview"] = bytes != null?Convert.ToBase64String(bytes) : null }; _logger.Trace("Got result: {json}", resultObj); return(resultObj); }
private async Task UpdateMediaInfo() { try { if (SpotifyMediaSession == null) { throw new Exception(); } GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = await SpotifyMediaSession.TryGetMediaPropertiesAsync(); GlobalSystemMediaTransportControlsSessionPlaybackControls mediaControls = SpotifyMediaSession.GetPlaybackInfo().Controls; CurrentArtist = mediaProperties.Artist.Length > 0 ? mediaProperties.Artist : mediaProperties.Title; IsAdPlaying = !mediaControls.IsNextEnabled || mediaProperties.Title == "Advertisement"; IsPlaying = mediaControls.IsPauseEnabled; } catch (Exception e) { Debug.WriteLine("UpdateMediaInfo exception " + e.ToString()); CurrentArtist = "N/A"; IsAdPlaying = false; IsPlaying = false; await RegisterSpotifyMediaSession(true); } }
private static void SmtcOnMediaPropertiesChanged(GlobalSystemMediaTransportControlsSession sender, MediaPropertiesChangedEventArgs args) { _mediaProperties = sender.TryGetMediaPropertiesAsync().GetAwaiter().GetResult(); MainWindow.Window.Dispatcher?.InvokeAsync(UpdateMediaProperties); }
public async void updateTrackInfo(GlobalSystemMediaTransportControlsSession session = null, GlobalSystemMediaTransportControlsSessionMediaProperties currentTrack = null) { await Task.Run(async() => { if (session == null) { session = await getSession(); } GlobalSystemMediaTransportControlsSessionMediaProperties nextTrack; bool shouldContinue; do { Thread.Sleep(200); nextTrack = await getMediaProperty(session); shouldContinue = nextTrack == null || isSameTrack(currentTrack, nextTrack); } while (shouldContinue); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { var playStatus = session.GetPlaybackInfo().PlaybackStatus; bool isPlaying = playStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing; togglePlayButton(isPlaying); var mediaProp = nextTrack; titleLabel.Text = mediaProp.Title; artistLabel.Text = mediaProp.Artist; statusMutex.WaitOne(); playbackStatus.title = mediaProp.Title; playbackStatus.artist = mediaProp.Artist; playbackStatus.album = mediaProp.AlbumTitle; playbackStatus.playing = isPlaying; playbackStatus.thumbnail = mediaProp.Thumbnail; statusMutex.ReleaseMutex(); if (mediaProp.Thumbnail != null) { try { var thumbnail = new BitmapImage(); await thumbnail.SetSourceAsync(await mediaProp.Thumbnail.OpenReadAsync()); albumArt.Source = thumbnail; var transform = new ScaleTransform(); transform.CenterX = -1; albumArt.RenderTransform = transform; } catch { albumArt.Source = null; } } }); }); }
//Update the currently playing media async Task UpdateCurrentMediaInformation() { try { //Check if volume is currently muted bool currentOutputVolumeMuted = AudioMuteGetStatus(false); bool currentInputVolumeMuted = AudioMuteGetStatus(true); await AVActions.ActionDispatcherInvokeAsync(delegate { img_Main_VolumeMute.Visibility = currentOutputVolumeMuted ? Visibility.Visible : Visibility.Collapsed; img_Main_MicrophoneMute.Visibility = currentInputVolumeMuted ? Visibility.Visible : Visibility.Collapsed; }); //Check if the application window is activated if (!vAppActivated) { //Debug.WriteLine("Not updating media information, not activated."); return; } //Check if the media popup is opened or setting is enabled bool mediaUpdateSetting = Convert.ToBoolean(Setting_Load(vConfigurationCtrlUI, "ShowMediaMain")); await AVActions.ActionDispatcherInvokeAsync(delegate { if (!mediaUpdateSetting) { main_Media_Information.Visibility = Visibility.Collapsed; //Debug.WriteLine("Not updating media information, disabled."); return; } else { //Update the media information margin double widthTopButtons = stackpanel_TopButtons.ActualWidth + 10; double widthClockBattery = grid_ClockBattery.ActualWidth + grid_ClockBattery.Margin.Right + 10; main_Media_Information.Margin = new Thickness(widthTopButtons, 10, widthClockBattery, 0); } }); //Get the media session manager GlobalSystemMediaTransportControlsSessionManager smtcSessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync(); if (smtcSessionManager == null) { HideMediaInformation(); return; } //Get the current media session GlobalSystemMediaTransportControlsSession smtcSession = smtcSessionManager.GetCurrentSession(); if (smtcSession == null) { HideMediaInformation(); return; } GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = await smtcSession.TryGetMediaPropertiesAsync(); GlobalSystemMediaTransportControlsSessionPlaybackInfo mediaPlayInfo = smtcSession.GetPlaybackInfo(); //Debug.WriteLine("Media: " + mediaProperties.Title + "/" + mediaProperties.Artist + "/" + mediaProperties.AlbumTitle + "/" + mediaProperties.Subtitle + "/" + mediaProperties.PlaybackType + "/" + mediaProperties.TrackNumber + "/" + mediaProperties.AlbumTrackCount); //Debug.WriteLine("Play: " + mediaPlayInfo.PlaybackStatus + "/" + mediaPlayInfo.PlaybackType); //Load the media artist string mediaArtist = mediaProperties.Artist; if (string.IsNullOrWhiteSpace(mediaArtist)) { mediaArtist = mediaProperties.Subtitle; if (string.IsNullOrWhiteSpace(mediaArtist)) { mediaArtist = "Unknown artist"; } } //Load the media title string mediaTitle = mediaProperties.Title; if (string.IsNullOrWhiteSpace(mediaTitle)) { mediaTitle = "Unknown title"; } //Update the media and volume information AVActions.ActionDispatcherInvoke(delegate { main_Media_Information_Artist.Text = mediaArtist; main_Media_Information_Title.Text = " " + mediaTitle; main_Media_Information.Visibility = Visibility.Visible; if (mediaPlayInfo.PlaybackStatus == GlobalSystemMediaTransportControlsSessionPlaybackStatus.Playing) { main_Media_Information_Artist.Opacity = 1; main_Media_Information_Title.Opacity = 1; } else { main_Media_Information_Artist.Opacity = 0.40; main_Media_Information_Title.Opacity = 0.40; } }); } catch { //Debug.WriteLine("Failed updating playing media."); HideMediaInformation(); } }
private static void MediaManager_OnSongChanged(MediaManager.MediaSession sender, GlobalSystemMediaTransportControlsSessionMediaProperties args) { WriteLineColor($"{sender.ControlSession.SourceAppUserModelId} is now playing {args.Title} {(string.IsNullOrEmpty(args.Artist) ? "" : $"by {args.Artist}")}", ConsoleColor.Cyan);
private void CurrentSession_OnMediaPropertyChanged(MediaSession mediaSession, GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties) { Application.Current.Dispatcher.Invoke(() => { UpdateUI(mediaSession); }); }
public bool isSameTrack(GlobalSystemMediaTransportControlsSessionMediaProperties one, GlobalSystemMediaTransportControlsSessionMediaProperties two) { return(!(one == null || two == null) && (one.Title == two.Title && one.Artist == two.Artist)); }
//Update the currently playing media async Task UpdateCurrentMediaInformation() { try { //Check if volume is currently muted bool currentOutputVolumeMuted = AudioMuteGetStatus(false); bool currentInputVolumeMuted = AudioMuteGetStatus(true); AVActions.ActionDispatcherInvoke(delegate { img_Main_VolumeMute.Visibility = currentOutputVolumeMuted ? Visibility.Visible : Visibility.Collapsed; img_Main_MicrophoneMute.Visibility = currentInputVolumeMuted ? Visibility.Visible : Visibility.Collapsed; }); //Get the current audio volume and mute status string currentVolumeString = string.Empty; int currentVolumeInt = AudioVolumeGet(false); if (currentVolumeInt >= 0) { currentVolumeString = "Volume " + currentVolumeInt + "%"; if (currentOutputVolumeMuted) { currentVolumeString += " (Muted)"; } } //Update the media and volume information AVActions.ActionDispatcherInvoke(delegate { textblock_Volume_Level.Text = currentVolumeString; }); //Get the media session manager GlobalSystemMediaTransportControlsSessionManager smtcSessionManager = await GlobalSystemMediaTransportControlsSessionManager.RequestAsync(); if (smtcSessionManager == null) { HideMediaInformation(); return; } //Get the current media session GlobalSystemMediaTransportControlsSession smtcSession = smtcSessionManager.GetCurrentSession(); if (smtcSession == null) { HideMediaInformation(); return; } GlobalSystemMediaTransportControlsSessionTimelineProperties mediaTimeline = smtcSession.GetTimelineProperties(); GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = await smtcSession.TryGetMediaPropertiesAsync(); GlobalSystemMediaTransportControlsSessionPlaybackInfo mediaPlayInfo = smtcSession.GetPlaybackInfo(); //Debug.WriteLine("Media: " + mediaProperties.Title + "/" + mediaProperties.Artist + "/" + mediaProperties.AlbumTitle + "/" + mediaProperties.Subtitle + "/" + mediaProperties.PlaybackType + "/" + mediaProperties.TrackNumber + "/" + mediaProperties.AlbumTrackCount); //Debug.WriteLine("Time: " + mediaTimeline.Position + "/" + mediaTimeline.StartTime + "/" + mediaTimeline.EndTime); //Debug.WriteLine("Play: " + mediaPlayInfo.PlaybackStatus + "/" + mediaPlayInfo.PlaybackType); //Load the media artist string mediaArtist = mediaProperties.Artist; if (string.IsNullOrWhiteSpace(mediaArtist)) { mediaArtist = mediaProperties.Subtitle; if (string.IsNullOrWhiteSpace(mediaArtist)) { mediaArtist = "Unknown artist"; } } //Load the track number string mediaTrackNumber = string.Empty; int currentTrackNumber = mediaProperties.TrackNumber; if (currentTrackNumber > 0) { int totalTrackNumber = mediaProperties.AlbumTrackCount; if (totalTrackNumber > 0) { mediaTrackNumber = "(" + currentTrackNumber + "/" + totalTrackNumber + ") "; } else { mediaTrackNumber = "(" + currentTrackNumber + ") "; } } //Load the media title string mediaTitle = mediaProperties.Title; if (string.IsNullOrWhiteSpace(mediaTitle)) { mediaTitle = mediaTrackNumber + "Unknown title"; } else { mediaTitle = mediaTrackNumber + mediaTitle; } //Load the media album title string mediaAlbum = mediaProperties.AlbumTitle; if (string.IsNullOrWhiteSpace(mediaAlbum)) { AVActions.ActionDispatcherInvoke(delegate { button_Information_Album.Visibility = Visibility.Collapsed; }); } else { AVActions.ActionDispatcherInvoke(delegate { button_Information_Album.Visibility = Visibility.Visible; }); } //Calculate the media progression double mediaProgress = 0; if (mediaTimeline.Position != new TimeSpan() && mediaTimeline.EndTime != new TimeSpan()) { mediaProgress = mediaTimeline.Position.TotalSeconds * 100 / mediaTimeline.EndTime.TotalSeconds; AVActions.ActionDispatcherInvoke(delegate { button_Information_Progress.Visibility = Visibility.Visible; }); } else { AVActions.ActionDispatcherInvoke(delegate { button_Information_Progress.Visibility = Visibility.Collapsed; }); } //Load the media thumbnail image BitmapFrame thumbnailBitmap = await GetMediaThumbnail(mediaProperties.Thumbnail); //Update the media and volume information AVActions.ActionDispatcherInvoke(delegate { button_Information_Artist.Text = mediaArtist; button_Information_Title.Text = mediaTitle; button_Information_Album.Text = mediaAlbum; button_Information_Progress.Value = mediaProgress; if (thumbnailBitmap != null) { button_Information_Thumbnail.Source = thumbnailBitmap; } else { button_Information_Thumbnail.Source = FileToBitmapImage(new string[] { "Assets/Default/Icons/Music.png" }, vImageSourceFolders, vImageBackupSource, IntPtr.Zero, -1, 0); } stackpanel_MediaPlaying.Visibility = Visibility.Visible; stackpanel_MediaNone.Visibility = Visibility.Collapsed; }); } catch { //Debug.WriteLine("Failed updating playing media."); HideMediaInformation(); } }
private static void Main(string[] args) { Console.OutputEncoding = System.Text.Encoding.UTF8; Console.Title = "Discord Rich Presence for Groove"; Client.DefaultRequestHeaders["User-Agent"] = "c#"; Console.WriteLine(AppDomain.CurrentDomain.BaseDirectory); Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); GenerateShortcuts(); if (args.Length > 0) { return; } LoadSettings(); foreach (DiscordRpcClient client in DefaultClients.Values) { if (!AllClients.ContainsKey(client.ApplicationID)) { AllClients.Add(client.ApplicationID, client); } else { AllClients[client.ApplicationID] = client; } } MetaTimer.Start(); Timer.Start(); UpdateTimer.Start(); CheckForUpdate(); foreach (DiscordRpcClient client in AllClients.Values) { client.Initialize(); client.OnError += _client_OnError; client.OnPresenceUpdate += _client_OnPresenceUpdate; } GlobalSystemMediaTransportControlsSessionMediaProperties currentTrack = null, lastTrack = null; try { currentTrack = GetStuff(); lastTrack = currentTrack; } catch (Exception) { } bool isPlaying = IsUsingAudio(), wasPlaying; while (IsInitialized()) { try { //limit performace impact if (UpdateTimer.ElapsedMilliseconds > updateCheckInterval) { CheckForUpdate(); } Thread.Sleep(2000); wasPlaying = isPlaying; try { isPlaying = IsUsingAudio(); } catch (Exception) { isPlaying = false; } if (wasPlaying && !isPlaying) { Timer.Restart(); } if (EnabledClients.ContainsKey(playerName) && EnabledClients[playerName] && (isPlaying || Timer.ElapsedMilliseconds < timeout_seconds * 1000)) { try { if (isPlaying) { lastTrack = currentTrack; } currentTrack = GetStuff(); if (wasPlaying && !isPlaying) { Console.WriteLine(currentAlbum + " and " + new Album(currentTrack.AlbumTitle, currentTrack.Artist, currentTrack.AlbumArtist)); activeClient.UpdateSmallAsset("paused", "paused"); activeClient.Invoke(); SetConsole(lastTrack.Title, lastTrack.Artist, lastTrack.AlbumTitle, currentAlbum); } else if ( /*(!currentAlbum.Equals(new Album(currentTrack.AlbumTitle, currentTrack.Artist, * currentTrack.AlbumArtist)) || playerName != lastPlayer || currentTrack.Title != lastTrack.Title) &&*/ isPlaying) { currentAlbum = new Album(currentTrack.AlbumTitle, currentTrack.Artist, currentTrack.AlbumArtist); if (ContainsAlbum(AlbumKeyMapping.Keys.ToArray(), currentAlbum)) { activeClient = GetBestClient(GetAlbum(AlbumKeyMapping, currentAlbum)); } else if (DefaultClients.ContainsKey(playerName)) { activeClient = DefaultClients[playerName]; } else { activeClient = DefaultClients[""]; } if (activeClient == null) { activeClient = DefaultClients[playerName]; Console.WriteLine("Uh oh!!!"); } string details = $"Title: {currentTrack.Title}", state = $"Artist: {(currentTrack.Artist == "" ? "Unkown Artist" : currentTrack.Artist)}"; if (activeClient.CurrentPresence == null || activeClient.CurrentPresence.Details != details.Substring(0, Math.Min(32, details.Length)) || activeClient.CurrentPresence.State != state.Substring(0, Math.Min(32, state.Length)) || wasPlaying != isPlaying) { #if DEBUG Console.WriteLine("Using " + activeClient.ApplicationID + " (" + (ContainsAlbum(AlbumKeyMapping.Keys.ToArray(), currentAlbum) && GetAlbum(AlbumKeyMapping, currentAlbum) .ContainsKey(activeClient.ApplicationID) && GetAlbum(AlbumKeyMapping, currentAlbum)[activeClient.ApplicationID].Length <= 32 ? GetAlbum(AlbumKeyMapping, currentAlbum)[activeClient.ApplicationID] : BigAssets[playerName]) + ")"); #endif presenceIsRich = ContainsAlbum(AlbumKeyMapping.Keys.ToArray(), currentAlbum) && GetAlbum(AlbumKeyMapping, currentAlbum) .ContainsKey(activeClient.ApplicationID); WrongArtistFlag = HasNameNotQuite(new Album(currentTrack.AlbumTitle)); if (ScreamAtUser && !presenceIsRich && !NotifiedAlbums.Contains(currentAlbum) && currentAlbum.Name != "") { NotifiedAlbums.Add(currentAlbum); if (WrongArtistFlag) { SendNotification("Album keyed wrong", currentAlbum.Name + " is keyed for a different artist (check caps). To disable these notifications, set verbose to false in DiscordPresenceConfig.ini"); } else { SendNotification("Album not keyed", currentAlbum.Name + " is not keyed. To disable these notifications, set verbose to false in DiscordPresenceConfig.ini"); } } activeClient.SetPresence(new RichPresence { Details = details.Length > 32 ? details.Substring(0, 32) : details, State = state.Length > 32 ? state.Substring(0, 32) : state, Assets = new Assets { LargeImageKey = ContainsAlbum(AlbumKeyMapping.Keys.ToArray(), currentAlbum) && GetAlbum(AlbumKeyMapping, currentAlbum) .ContainsKey(activeClient.ApplicationID) && GetAlbum(AlbumKeyMapping, currentAlbum)[activeClient.ApplicationID] .Length <= 32 ? GetAlbum(AlbumKeyMapping, currentAlbum)[ activeClient.ApplicationID] : BigAssets[playerName], LargeImageText = currentTrack.AlbumTitle.Length > 0 ? currentTrack.AlbumTitle.Length <= 2 ? "_" + currentTrack.AlbumTitle + "_" : currentTrack.AlbumTitle.Length > 128 ? currentTrack.AlbumTitle.Substring(0, 128) : currentTrack.AlbumTitle : "Unknown Album", SmallImageKey = isPlaying ? (LittleAssets.ContainsKey(playerName) ? LittleAssets[playerName] : defaultPlayer) : "paused", SmallImageText = isPlaying ? ("Using " + Aliases[playerName]) : "paused" } }); SetConsole(currentTrack.Title, currentTrack.Artist, currentTrack.AlbumTitle, currentAlbum); activeClient.Invoke(); } foreach (DiscordRpcClient client in AllClients.Values) { if (client.CurrentPresence != null && client.ApplicationID != activeClient.ApplicationID) { #if DEBUG Console.WriteLine("Cleared " + client.ApplicationID); #endif client.ClearPresence(); try { client.Invoke(); } catch (Exception) { } } } } #if DEBUG Console.Write("" + (MetaTimer.ElapsedMilliseconds) + "(" + (Timer.ElapsedMilliseconds /* < timeout_seconds * 1000*/) + ") in " + playerName + '\r'); #endif } catch (Exception e) { #if DEBUG Console.WriteLine(e.StackTrace); #else Console.WriteLine(e.Message); #endif if (activeClient != null) { activeClient.SetPresence(new RichPresence() { Details = "Failed to get track info" }); } Console.Write("Failed to get track info \r"); } } else if (!EnabledClients.ContainsKey(playerName)) { SetUnknown(); foreach (DiscordRpcClient client in AllClients.Values) { if (client.CurrentPresence != null) { client.ClearPresence(); client.Invoke(); } } } else { SetClear(); #if DEBUG Console.Write("Cleared " + (MetaTimer.ElapsedMilliseconds) + "\r"); #endif foreach (DiscordRpcClient client in AllClients.Values) { if (client != null && client.CurrentPresence != null) { client.ClearPresence(); //client.Invoke(); } } } } catch (Exception e) { Console.WriteLine(e.Message); Console.WriteLine(e.StackTrace); Console.WriteLine("Something unexpected has occured"); } } }
private static async void SetPlaybackInfoMediaProperties() { while (mediaPropertiesLock) { Thread.Sleep(100); } mediaPropertiesLock = true; if (globalSystemMediaTransportControlsSession == null) { artist = ""; title = ""; thumbnailBitmap = null; } else { GlobalSystemMediaTransportControlsSessionMediaProperties mediaProperties = null; try { mediaProperties = await globalSystemMediaTransportControlsSession.TryGetMediaPropertiesAsync(); } catch (Exception ex) { artist = ""; title = ""; thumbnail = null; mediaPropertiesChanged = true; mediaPropertiesLock = false; return; } artist = mediaProperties.Artist; title = mediaProperties.Title; var thumbnailOpenRead = mediaProperties.Thumbnail; if (thumbnailOpenRead != null) { var thumbnailOpenReadStream = await thumbnailOpenRead.OpenReadAsync(); if (thumbnailOpenReadStream.CanRead) { thumbnail = new byte[thumbnailOpenReadStream.Size]; await thumbnailOpenReadStream.ReadAsync(thumbnail.AsBuffer(), (uint)thumbnailOpenReadStream.Size, InputStreamOptions.None); using (MemoryStream ms = new MemoryStream(thumbnail)) { ms.Position = 0; thumbnailBitmap = new System.Drawing.Bitmap(ms); using (MemoryStream stream = new MemoryStream()) { thumbnailBitmap.Save(stream, System.Drawing.Imaging.ImageFormat.Jpeg); // Konwersja ze względu na błąd po stronie Androida w przypadku przesyłania pliku *.png: [skia] ------ png error IDAT: CRC error [skia] ---codec->getAndroidPixels() failed. thumbnail = stream.ToArray(); } } } else { thumbnail = null; } } else { thumbnail = null; } } mediaPropertiesChanged = true; mediaPropertiesLock = false; }