forked from ashpynov/PlayniteSound
-
Notifications
You must be signed in to change notification settings - Fork 0
/
PlayniteSounds.cs
2341 lines (1948 loc) · 85.7 KB
/
PlayniteSounds.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Playnite.SDK;
using Playnite.SDK.Models;
using Playnite.SDK.Plugins;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Input;
using System.Runtime.InteropServices;
using System.Media;
using System.ComponentModel;
using Playnite.SDK.Events;
using System.Diagnostics;
using Microsoft.Win32;
using System.Windows;
using System.IO.Compression;
using System.Threading;
using PlayniteSounds.Downloaders;
using PlayniteSounds.Common;
using PlayniteSounds.Common.Constants;
using PlayniteSounds.Models;
using PlayniteSounds.Controls;
using PlayniteSounds.ViewModels;
using System.Threading.Tasks;
using System.Data;
namespace PlayniteSounds
{
class SDL_mixer
{
const string nativeLibName = "SDL2_mixer";
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern int Mix_HaltMusic();
[DllImport(nativeLibName, CallingConvention = CallingConvention.Cdecl)]
public static extern void Mix_FreeMusic(IntPtr music);
}
public class PlayniteSounds : GenericPlugin
{
public bool ReloadMusic { get; set; }
public static IPlayniteAPI playniteAPI;
private static readonly string PluginFolder = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
private static readonly string IconPath = Path.Combine(PluginFolder, "icon.png");
private static readonly Lazy<string> HelpMessage = new Lazy<string>(() =>
Resource.MsgHelp1 + "\n\n" +
Resource.MsgHelp2 + "\n\n" +
Resource.MsgHelp3 + " " +
Resource.MsgHelp4 + " " +
Resource.MsgHelp5 + "\n\n" +
Resource.MsgHelp6 + "\n\n" +
HelpLine(SoundFile.BaseApplicationStartedSound) +
HelpLine(SoundFile.BaseApplicationStoppedSound) +
HelpLine(SoundFile.BaseGameInstalledSound) +
HelpLine(SoundFile.BaseGameSelectedSound) +
HelpLine(SoundFile.BaseGameStartedSound) +
HelpLine(SoundFile.BaseGameStartingSound) +
HelpLine(SoundFile.BaseGameStoppedSound) +
HelpLine(SoundFile.BaseGameUninstalledSound) +
HelpLine(SoundFile.BaseLibraryUpdatedSound) +
Resource.MsgHelp7);
private static readonly ILogger Logger = LogManager.GetLogger();
private IDownloadManager DownloadManager;
public PlayniteSoundsSettingsViewModel SettingsModel { get; }
private bool _gameRunning;
private bool _musicEnded;
private bool _firstSelectSound = true;
private bool _closeAudioFilesNextPlay;
private string _prevMusicFileName = string.Empty; //used to prevent same file being restarted
private readonly string _extraMetaDataFolder;
private readonly string _musicFilesDataPath;
private readonly string _soundFilesDataPath;
private readonly string _soundManagerFilesDataPath;
private readonly string _defaultMusicPath;
private readonly string _gameMusicFilePath;
private readonly string _platformMusicFilePath;
private readonly string _filterMusicFilePath;
private readonly Dictionary<string, PlayerEntry> _players = new Dictionary<string, PlayerEntry>();
private MediaPlayer _musicPlayer;
private MusicFader _musicFader;
private readonly MediaTimeline _timeLine;
private readonly List<GameMenuItem> _gameMenuItems;
private readonly List<MainMenuItem> _mainMenuItems;
private ISet<string> _pausers = new HashSet<string>();
static public dynamic FullscreenSettings;
#region Constructor
public PlayniteSounds(IPlayniteAPI api) : base(api)
{
playniteAPI = api;
try
{
FullscreenSettings = PlayniteApi.ApplicationSettings.Fullscreen
.GetType()
.GetField("settings", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(PlayniteApi.ApplicationSettings.Fullscreen);
SoundFile.ApplicationInfo = PlayniteApi.ApplicationInfo;
_extraMetaDataFolder = Path.Combine(api.Paths.ConfigurationPath, SoundDirectory.ExtraMetaData);
_musicFilesDataPath = Path.Combine(_extraMetaDataFolder, SoundDirectory.Music);
_soundFilesDataPath = Path.Combine(_extraMetaDataFolder, SoundDirectory.Sound);
_soundManagerFilesDataPath = Path.Combine(_extraMetaDataFolder, SoundDirectory.SoundManager);
_defaultMusicPath = Path.Combine(_extraMetaDataFolder, SoundDirectory.Default);
Directory.CreateDirectory(_defaultMusicPath);
_platformMusicFilePath = Path.Combine(_extraMetaDataFolder, SoundDirectory.Platform);
Directory.CreateDirectory(_platformMusicFilePath);
_filterMusicFilePath = Path.Combine(_extraMetaDataFolder, SoundDirectory.Filter);
Directory.CreateDirectory(_filterMusicFilePath);
_gameMusicFilePath = Path.Combine(_extraMetaDataFolder, SoundDirectory.GamesFolder);
Directory.CreateDirectory(_gameMusicFilePath);
SettingsModel = new PlayniteSoundsSettingsViewModel(this);
SettingsModel.Settings.PropertyChanged += OnSettingsChanged;
Properties = new GenericPluginProperties
{
HasSettings = true
};
Localization.SetPluginLanguage(PluginFolder, api.ApplicationSettings.Language);
_musicPlayer = new MediaPlayer();
_musicPlayer.MediaEnded += MediaEnded;
_musicFader = new MusicFader(_musicPlayer, Settings);
_timeLine = new MediaTimeline();
//{
// RepeatBehavior = RepeatBehavior.Forever
//};
_gameMenuItems = new List<GameMenuItem>
{
ConstructGameMenuItem(Resource.Youtube, _ => DownloadMusicForSelectedGames(Source.Youtube), "|" + Resource.Actions_Download),
ConstructGameMenuItem(Resource.ActionsCopySelectMusicFile, SelectMusicForSelectedGames),
ConstructGameMenuItem(Resource.ActionsOpenSelected, OpenMusicDirectory),
ConstructGameMenuItem(Resource.ActionsDeleteSelected, DeleteMusicDirectories),
ConstructGameMenuItem(Resource.Actions_Normalize, CreateNormalizationDialogue),
};
_mainMenuItems = new List<MainMenuItem>
{
ConstructMainMenuItem(Resource.ActionsOpenMusicFolder, OpenMusicFolder),
ConstructMainMenuItem(Resource.ActionsOpenSoundsFolder, OpenSoundsFolder),
ConstructMainMenuItem(Resource.ActionsReloadAudioFiles, ReloadAudioFiles),
ConstructMainMenuItem(Resource.ActionsHelp, HelpMenu),
new MainMenuItem { Description = "-", MenuSection = App.MainMenuName },
ConstructMainMenuItem(Resource.ActionsCopySelectMusicFile, SelectMusicForDefault, "|" + Resource.ActionsDefault),
};
DownloadManager = new DownloadManager(Settings, Path.Combine(_musicFilesDataPath,"tmp"));
PlayniteApi.Database.Games.ItemCollectionChanged += CleanupDeletedGames;
PlayniteApi.Database.Platforms.ItemCollectionChanged += UpdatePlatforms;
PlayniteApi.Database.FilterPresets.ItemCollectionChanged += UpdateFilters;
PlayniteApi.UriHandler.RegisterSource("Sounds", HandleUriEvent);
#region Control constructor
AddCustomElementSupport(new AddCustomElementSupportArgs
{
SourceName = "Sounds",
ElementList = new List<string> { "MusicControl" }
});
#endregion
AddSettingsSupport(new AddSettingsSupportArgs
{
SourceName = "Sounds",
SettingsRoot = $"{nameof(SettingsModel)}.{nameof(SettingsModel.Settings)}"
});
if (SettingsModel.Settings.PauseOnTrailer)
MediaElementsMonitor.Attach(PlayniteApi, SettingsModel.Settings);
if (PlayniteApi.ApplicationInfo.Mode == ApplicationMode.Fullscreen)
{
(GetFullscreenMainModel() as ObservableObject).PropertyChanged += OnFullscreenChanged;
}
SupressNativeFulscreenMusic();
}
catch (Exception e)
{
HandleException(e);
}
}
public void OnFullscreenChanged( object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == "GameDetailsVisible")
{
SettingsModel.Settings.GameDetailsVisible = GetFullscreenMainModel().GameDetailsVisible;
if ( SettingsModel.Settings.DetailsMusicType != MusicType.Same
&& SettingsModel.Settings.DetailsMusicType != SettingsModel.Settings.MusicType)
{
ReplayMusic();
}
}
}
private dynamic GetFullscreenMainModel()
{
return PlayniteApi.MainView
.GetType()
.GetField("mainModel", BindingFlags.NonPublic | BindingFlags.Instance)
.GetValue(PlayniteApi.MainView);
}
private void SupressNativeFulscreenMusic()
{
if ( PlayniteApi.ApplicationInfo.Mode != ApplicationMode.Fullscreen
|| SettingsModel.Settings.MusicState == AudioState.Desktop)
return;
dynamic backgroundMusicProperty = GetFullscreenMainModel().App
.GetType()
.GetProperty("BackgroundMusic");
IntPtr currentMusic = (IntPtr)backgroundMusicProperty.GetValue(null);
if (currentMusic != new IntPtr(0))
{
// stop music
SDL_mixer.Mix_HaltMusic();
SDL_mixer.Mix_FreeMusic(currentMusic);
backgroundMusicProperty.GetSetMethod(true).Invoke(null, new[] { new IntPtr(0) as object});
}
}
private void Fullscreen_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(FullscreenSettings.BackgroundVolume))
{
ResetMusicVolume();
}
}
public void UpdateDownloadManager(PlayniteSoundsSettings settings)
=> DownloadManager = new DownloadManager(settings, Path.Combine(_musicFilesDataPath,"tmp"));
private static string HelpLine(string baseMessage)
=> $"{SoundFile.DesktopPrefix}{baseMessage} - {SoundFile.FullScreenPrefix}{baseMessage}\n";
#region Control registration
public override Control GetGameViewControl(GetGameViewControlArgs args)
{
var strArgs = args.Name.Split('_');
var controlType = strArgs[0];
switch (controlType)
{
case "MusicControl":
return new MusicControl(SettingsModel.Settings);
default:
throw new ArgumentException($"Unrecognized controlType '{controlType}' for request '{args.Name}'");
}
}
#endregion
#endregion
#region Playnite Interface
public override Guid Id { get; } = Guid.Parse("9c960604-b8bc-4407-a4e4-e291c6097c7d");
public override ISettings GetSettings(bool firstRunSettings) => SettingsModel;
public override UserControl GetSettingsView(bool firstRunSettings) => new PlayniteSoundsSettingsView(this);
public override void OnGameInstalled(OnGameInstalledEventArgs args)
=> PlaySoundFileFromName(SoundFile.GameInstalledSound);
public override void OnGameUninstalled(OnGameUninstalledEventArgs args)
=> PlaySoundFileFromName(SoundFile.GameUninstalledSound);
public override void OnGameSelected(OnGameSelectedEventArgs args)
{
if (!(_firstSelectSound && Settings.SkipFirstSelectSound))
{
PlaySoundFileFromName(SoundFile.GameSelectedSound);
}
_firstSelectSound = false;
PlayMusicBasedOnSelected();
}
public override void OnGameStarted(OnGameStartedEventArgs args)
{
if (Settings.StopMusic)
{
PauseMusic();
_gameRunning = true;
}
PlaySoundFileFromName(SoundFile.GameStartedSound, true);
}
public override void OnGameStarting(OnGameStartingEventArgs args)
{
if (!Settings.StopMusic)
{
PauseMusic();
_gameRunning = true;
}
PlaySoundFileFromName(SoundFile.GameStartingSound);
}
public override void OnGameStopped(OnGameStoppedEventArgs args)
{
_gameRunning = false;
PlaySoundFileFromName(SoundFile.GameStoppedSound);
ResumeMusic();
}
public override void OnApplicationStarted(OnApplicationStartedEventArgs args)
{
// One-time operations
UpdateFromLegacyVersion();
CopyAudioFiles();
PlaySoundFileFromName(SoundFile.ApplicationStartedSound);
SystemEvents.PowerModeChanged += OnPowerModeChanged;
Application.Current.MainWindow.StateChanged += OnWindowStateChanged;
Application.Current.Deactivated += OnApplicationDeactivate;
Application.Current.Activated += OnApplicationActivate;
dynamic ctx = Application.Current.MainWindow.DataContext;
(ctx.AppSettings.Fullscreen as INotifyPropertyChanged).PropertyChanged += Fullscreen_PropertyChanged;
// Application.Current.MainWindow.KeyDown += (_, e) =>
// {
// if (e.Key == Key.MediaNextTrack)
// {
// PlayMusicBasedOnSelected();
// e.Handled = true;
// }
// };
}
public override void OnApplicationStopped(OnApplicationStoppedEventArgs args)
{
// Add code to be executed when Playnite is shutting down.
SystemEvents.PowerModeChanged -= OnPowerModeChanged;
Application.Current.Deactivated -= OnApplicationDeactivate;
Application.Current.Activated -= OnApplicationActivate;
if (Application.Current.MainWindow != null)
{
Application.Current.MainWindow.StateChanged -= OnWindowStateChanged;
}
PlaySoundFileFromName(SoundFile.ApplicationStoppedSound, true);
CloseAudioFiles();
CloseMusic();
_musicPlayer.MediaEnded -= MediaEnded;
_musicFader.Destroy();
_musicFader = null;
_musicPlayer = null;
}
public override void OnLibraryUpdated(OnLibraryUpdatedEventArgs args)
{
// Add code to be executed when library is updated.
PlaySoundFileFromName(SoundFile.LibraryUpdatedSound);
if (Settings.AutoDownload)
{
var games = PlayniteApi.Database.Games
.Where(x => x.Added != null && x.Added > Settings.LastAutoLibUpdateAssetsDownload);
MuteExceptions();
CreateDownloadDialogue(games, Source.All);
UnMuteExceptions();
}
Settings.LastAutoLibUpdateAssetsDownload = DateTime.Now;
SavePluginSettings(Settings);
}
public override IEnumerable<GameMenuItem> GetGameMenuItems(GetGameMenuItemsArgs args)
{
var gameMenuItems = new List<GameMenuItem>();
if (Settings.Downloaders.Contains(Source.KHInsider))
{
gameMenuItems.Add(ConstructGameMenuItem(
"All", _ => DownloadMusicForSelectedGames(Source.All), "|" + Resource.Actions_Download));
gameMenuItems.Add(ConstructGameMenuItem(
"KHInsider", _ => DownloadMusicForSelectedGames(Source.KHInsider), "|" + Resource.Actions_Download));
}
gameMenuItems.AddRange(_gameMenuItems);
if (SingleGame())
{
var files = Directory.GetFiles(CreateMusicDirectory(SelectedGames.First()));
if (files.Any())
{
gameMenuItems.Add(new GameMenuItem { Description = "-", MenuSection = App.AppName });
gameMenuItems.AddRange(ConstructItems(ConstructGameMenuItem, files, "|", true));
}
}
return gameMenuItems;
}
public override IEnumerable<MainMenuItem> GetMainMenuItems(GetMainMenuItemsArgs args)
{
var mainMenuItems = new List<MainMenuItem>(_mainMenuItems);
mainMenuItems.AddRange(CreateDirectoryMainMenuItems(
PlayniteApi.Database.Platforms,
Resource.ActionsPlatform,
CreatePlatformDirectory,
SelectMusicForPlatform));
mainMenuItems.AddRange(CreateDirectoryMainMenuItems(
PlayniteApi.Database.FilterPresets,
Resource.ActionsFilter,
CreateFilterDirectory,
SelectMusicForFilter));
var defaultSubMenu = $"|{Resource.ActionsDefault}";
var defaultFiles = Directory.GetFiles(_defaultMusicPath);
if (defaultFiles.Any())
{
mainMenuItems.Add(new MainMenuItem
{
Description = "-",
MenuSection = App.MainMenuName + defaultSubMenu
});
mainMenuItems.AddRange(ConstructItems(ConstructMainMenuItem, defaultFiles, defaultSubMenu + "|"));
}
return mainMenuItems;
}
private IEnumerable<MainMenuItem> CreateDirectoryMainMenuItems<T>(
IEnumerable<T> databaseObjects,
string menuPath,
Func<T, string> directoryConstructor,
Action<T> musicSelector) where T : DatabaseObject
{
foreach (var databaseObject in databaseObjects.OrderBy(o => o.Name))
{
var directorySelect = $"|{menuPath}|{databaseObject.Name}";
yield return ConstructMainMenuItem(
Resource.ActionsCopySelectMusicFile,
() => musicSelector(databaseObject),
directorySelect);
var files = Directory.GetFiles(directoryConstructor(databaseObject));
if (files.Any())
{
yield return new MainMenuItem
{
Description = "-",
MenuSection = App.MainMenuName + directorySelect
};
foreach (var item in ConstructItems(ConstructMainMenuItem, files, directorySelect + "|"))
{
yield return item;
}
}
}
}
private void CleanupDeletedGames(object sender, ItemCollectionChangedEventArgs<Game> ItemCollectionChangedArgs)
{
// Let ExtraMetaDataLoader handle cleanup if it exists
if (PlayniteApi.Addons.Plugins.Any(p => p.Id.ToString() is App.ExtraMetaGuid))
{
return;
}
foreach (var removedItem in ItemCollectionChangedArgs.RemovedItems)
{
DeleteMusicDirectory(removedItem);
}
}
private void UpdatePlatforms(object sender, ItemCollectionChangedEventArgs<Platform> ItemCollectionChangedArgs)
{
foreach (var addedItem in ItemCollectionChangedArgs.AddedItems)
{
CreatePlatformDirectory(addedItem.Name);
}
DeleteDirectories(ItemCollectionChangedArgs.RemovedItems, GetPlatformDirectoryPath);
}
private void UpdateFilters(object sender, ItemCollectionChangedEventArgs<FilterPreset> ItemCollectionChangedArgs)
{
foreach (var addedItem in ItemCollectionChangedArgs.AddedItems)
{
CreateFilterDirectory(addedItem.Id.ToString());
}
DeleteDirectories(ItemCollectionChangedArgs.RemovedItems, GetFilterDirectoryPath);
}
private void DeleteDirectories<T>(IEnumerable<T> directoryLinks, Func<T, string> PathConstructor)
=> directoryLinks.
Select(PathConstructor).
Where(Directory.Exists).
ForEach(f => Directory.Delete(f, true));
// ex: playnite://Sounds/Play/someId
// Sounds maintains a list of plugins who want the music paused and will only allow play when
// no other plugins have paused.
private void HandleUriEvent(PlayniteUriEventArgs args)
{
var action = args.Arguments[0];
var senderId = args.Arguments[1];
switch (action.ToLower())
{
case "play":
_pausers.Remove(senderId);
ResumeMusic();
break;
case "pause":
if (_pausers.Add(senderId) && _pausers.Count is 1)
{
PauseMusic();
}
break;
}
}
#endregion
#region State Changes
private void OnWindowStateChanged(object sender, EventArgs e)
{
if (Settings.PauseOnDeactivate)
{
switch (Application.Current?.MainWindow?.WindowState)
{
case WindowState.Normal:
case WindowState.Maximized:
ResumeMusic();
break;
case WindowState.Minimized:
PauseMusic();
break;
}
}
}
private void OnApplicationDeactivate(object sender, EventArgs e)
{
if (Settings.PauseOnDeactivate)
{
PauseMusic();
}
}
private void OnApplicationActivate(object sender, EventArgs e)
{
if (Settings.PauseOnDeactivate)
{
ResumeMusic();
}
}
//fix sounds not playing after system resume
private void OnPowerModeChanged(object sender, PowerModeChangedEventArgs args)
{
var shouldNotPlay = Settings.PauseOnDeactivate
&& Application.Current?.MainWindow?.WindowState == WindowState.Minimized;
if (args.Mode is PowerModes.Resume && !shouldNotPlay)
{
Try(RestartMusic);
}
}
public void OnSettingsChanged( object sender, PropertyChangedEventArgs args)
{
if (args.PropertyName == nameof(SettingsModel.Settings.VideoIsPlaying)
|| args.PropertyName == nameof(SettingsModel.Settings.PreviewIsPlaying))
{
if (SettingsModel.Settings.VideoIsPlaying
|| SettingsModel.Settings.PreviewIsPlaying )
PauseMusic();
else
ResumeMusic();
}
}
private void RestartMusic()
{
_closeAudioFilesNextPlay = true;
ReloadMusic = true;
ReplayMusic();
}
#endregion
#region Audio Player
public void ResetMusicVolume()
{
if (_musicPlayer != null && _musicPlayer.Volume != Settings.MusicVolume )
{
if (Settings.MusicVolume == 0)
{
PauseMusic();
}
else if (_musicPlayer.Volume == 0)
{
ResumeMusic();
}
_musicPlayer.Volume = Settings.MusicVolume / 100.0;
}
}
public void ReplayMusic()
{
if (SingleGame() && ShouldPlayMusicOrClose())
{
PlayMusicFromFirstSelected();
}
}
private void PlayMusicFromFirstSelected() => PlayMusicFromFirst(SelectedGames);
private List<string> CollectMusicFromSimilar(MusicType type, Game game = default)
{
List<string> files = new List<string>();
if (type == MusicType.Platform && game is null)
{
return files;
}
List<Game> similarGames = new List<Game>();
switch (type)
{
case MusicType.Platform:
similarGames = PlayniteApi.Database.Games.Where(g => g.PlatformIds.Intersect(game.PlatformIds).Any()).ToList();
break;
case MusicType.Filter:
similarGames = PlayniteApi.Database.GetFilteredGames(PlayniteApi.MainView.GetCurrentFilterSettings()).ToList();
break;
default:
similarGames = PlayniteApi.Database.Games.ToList();
break;
}
foreach( Game g in similarGames )
{
var path = GetMusicDirectoryPath(g);
if (Directory.Exists(path))
{
files.AddMissing(Directory.GetFiles(path));
}
}
return files;
}
private void PlayMusicFromFirst(IEnumerable<Game> games = null)
{
var game = games.FirstOrDefault();
string fileDirectory;
switch (Settings.ChoosenMusicType)
{
case MusicType.Game:
fileDirectory = CreateMusicDirectory(game);
break;
case MusicType.Platform:
fileDirectory = CreatePlatformDirectoryPathFromGame(game);
break;
case MusicType.Filter:
fileDirectory = CreateCurrentFilterDirectory();
break;
default:
fileDirectory = _defaultMusicPath;
break;
}
List<string> files = new List<string>(Directory.Exists(fileDirectory) ? Directory.GetFiles(fileDirectory) : new string[] { }) ;
if ( Settings.CollectFromGames && Settings.ChoosenMusicType != MusicType.Game )
{
files.AddMissing(CollectMusicFromSimilar(Settings.ChoosenMusicType, game));
}
if (Settings.PlayBackupMusic && !files.Any())
{
files = new List<string>(GetBackupFiles());
}
PlayMusicFromFiles(files);
}
private void PlayMusicFromFiles(List<string> musicFiles)
{
var musicFile = !string.IsNullOrEmpty(_prevMusicFileName) ? _prevMusicFileName : musicFiles.FirstOrDefault() ?? string.Empty;
var musicEndRandom = _musicEnded && Settings.RandomizeOnMusicEnd;
var rand = new Random();
var changedSelection = !musicFiles.Contains(_prevMusicFileName);
if ((changedSelection && musicFiles.Count > 0) || (musicFiles.Count > 1 && (Settings.RandomizeOnEverySelect || musicEndRandom)))
{
ReloadMusic = true;
do
{
musicFile = musicFiles[rand.Next(musicFiles.Count)];
}
while (_prevMusicFileName == musicFile);
}
else if ( changedSelection && musicFiles.Count == 0 )
{
musicFile = string.Empty;
}
PlayMusicFromPath(musicFile);
}
private void ResumeMusic()
{
if (ShouldPlayMusic())
{
if (_musicPlayer?.Clock != null)
{
Try(()=>_musicFader?.Resume());
}
else
{
PlayMusicBasedOnSelected();
}
}
}
private void PauseMusic()
{
if (_musicPlayer?.Clock != null)
{
Try(()=>_musicFader?.Pause());
}
}
private void CloseMusic()
{
if (_musicPlayer?.Clock != null)
{
Try(() => _musicFader?.Switch(SubCloseMusic, null));
}
}
private void SubCloseMusic()
{
if (_musicPlayer is null)
{
return;
}
_musicPlayer.Clock = null;
_musicPlayer.Close();
SettingsModel.Settings.CurrentMusicName = string.Empty;
}
private void ForcePlayMusicFromPath(string filePath)
{
ReloadMusic = true;
PlayMusicFromPath(filePath);
}
private void PlayMusicFromPath(string filePath)
{
//need to use directoryname on verification otherwise when game music randomly changes
//on musicend music will be restarted when we select another game in for Default or Platform Mode
//in case of "random music on selection" or "Random Music on Musicend" ReloadMusic will be set
//check on empty needs to happen before directory verification or exceptions occur if no such music exists
//it still needs to call the sub to play the music but it will just close the music as File.exists will fail there
if (ReloadMusic || _prevMusicFileName.Equals(string.Empty) || filePath.Equals(string.Empty) ||
(Path.GetDirectoryName(filePath) != Path.GetDirectoryName(_prevMusicFileName)))
{
if (File.Exists(filePath))
{
Try(() => _musicFader?.Switch(SubCloseMusic, () => SubPlayMusicFromPath(filePath)));
}
else
Try(() => _musicFader?.Switch(SubCloseAndStopMusic, null));
}
}
private void SubCloseAndStopMusic()
{
SubCloseMusic();
ReloadMusic = false;
_prevMusicFileName = string.Empty;
}
private void SubPlayMusicFromPath(string filePath)
{
ReloadMusic = false;
_prevMusicFileName = string.Empty;
if (File.Exists(filePath))
{
_prevMusicFileName = filePath;
_timeLine.Source = new Uri(filePath);
_musicPlayer.Clock = _timeLine.CreateClock();
_musicEnded = false;
SettingsModel.Settings.CurrentMusicName = Path.GetFileNameWithoutExtension(filePath);
}
}
private void PlaySoundFileFromName(string fileName, bool useSoundPlayer = false)
{
if (ShouldPlaySound())
{
Try(() => SubPlaySoundFileFromName(fileName, useSoundPlayer));
}
}
private void SubPlaySoundFileFromName(string fileName, bool useSoundPlayer)
{
if (_closeAudioFilesNextPlay)
{
CloseAudioFiles();
_closeAudioFilesNextPlay = false;
}
_players.TryGetValue(fileName, out var entry);
if (entry == null)
{
entry = CreatePlayerEntry(fileName, useSoundPlayer);
}
if (entry != null)
/*Then*/ if (useSoundPlayer)
{
entry.SoundPlayer.Stop();
entry.SoundPlayer.PlaySync();
}
else
{
entry.MediaPlayer.Stop();
entry.MediaPlayer.Play();
}
}
private PlayerEntry CreatePlayerEntry(string fileName, bool useSoundPlayer)
{
var fullFileName = Path.Combine(_extraMetaDataFolder, SoundDirectory.Sound, fileName);
if (!File.Exists(fullFileName))
{
return null;
}
var entry = new PlayerEntry();
if (useSoundPlayer)
{
entry.SoundPlayer = new SoundPlayer { SoundLocation = fullFileName };
entry.SoundPlayer.Load();
}
else
{
// MediaPlayer can play multiple sounds together from multiple instances, but the SoundPlayer can not
entry.MediaPlayer = new MediaPlayer();
entry.MediaPlayer.Open(new Uri(fullFileName));
}
return _players[fileName] = entry;
}
private void CloseAudioFiles()
{
foreach(var playerFile in _players.Keys.ToList())
{
var player = _players[playerFile];
_players.Remove(playerFile);
Try(() => CloseAudioFile(player));
}
}
private static void CloseAudioFile(PlayerEntry entry)
{
if (entry.MediaPlayer != null)
{
var filename = entry.MediaPlayer.Source == null
? string.Empty
: entry.MediaPlayer.Source.LocalPath;
entry.MediaPlayer.Stop();
entry.MediaPlayer.Close();
entry.MediaPlayer = null;
if (File.Exists(filename))
{
var fileInfo = new FileInfo(filename);
for (var count = 0; IsFileLocked(fileInfo) && count < 100; count++)
{
Thread.Sleep(5);
}
}
}
else
{
entry.SoundPlayer.Stop();
entry.SoundPlayer = null;
}
}
public void ReloadAudioFiles()
{
CloseAudioFiles();
ShowMessage(Resource.ActionsReloadAudioFiles);
}
private void MediaEnded(object sender, EventArgs e)
{
_musicEnded = true;
if (Settings.RandomizeOnMusicEnd)
{
// will play a random song if more than one exists
ReloadMusic = true;
ReplayMusic();
}
else if (_musicPlayer.Clock != null)
{
_musicPlayer.Clock.Controller.Stop();
_musicPlayer.Clock.Controller.Begin();
}
}
#endregion
#region UI
#region Menu UI
private IEnumerable<TMenuItem> ConstructItems<TMenuItem>(
Func<string, Action, string, TMenuItem> menuItemConstructor,
string[] files,
string subMenu,
bool isGame = false)
{
foreach (var file in files)
{
var songName = Path.GetFileNameWithoutExtension(file);
var songSubMenu = subMenu + songName;
yield return menuItemConstructor(
Resource.ActionsCopyPlayMusicFile, () => ForcePlayMusicFromPath(file), songSubMenu);
yield return menuItemConstructor(
Resource.ActionsCopyDeleteMusicFile, () => DeleteMusicFile(file, songName, isGame), songSubMenu);
}
}
private static GameMenuItem ConstructGameMenuItem(string resource, Action action, string subMenu = "")
=> ConstructGameMenuItem(resource, _ => action(), subMenu);
private static GameMenuItem ConstructGameMenuItem(
string resource, Action<GameMenuItemActionArgs> action, string subMenu = "") => new GameMenuItem
{
MenuSection = App.AppName + subMenu,
Icon = IconPath,
Description = resource,
Action = action
};
private static MainMenuItem ConstructMainMenuItem(string resource, Action action, string subMenu = "")
=> ConstructMainMenuItem(resource, _ => action(), subMenu);
private static MainMenuItem ConstructMainMenuItem(