18
18
using System . Threading . Tasks ;
19
19
using NAudio . CoreAudioApi ;
20
20
using NAudio . Wave ;
21
+ using Serilog ;
21
22
using SoundSwitch . Framework . Audio ;
22
23
using SoundSwitch . Framework . NotificationManager . Notification . Configuration ;
23
24
using SoundSwitch . Localization ;
@@ -26,6 +27,7 @@ namespace SoundSwitch.Framework.NotificationManager.Notification
26
27
{
27
28
public class NotificationSound : INotification
28
29
{
30
+ private CancellationTokenSource _cancellationTokenSource ;
29
31
public NotificationTypeEnum TypeEnum => NotificationTypeEnum . SoundNotification ;
30
32
public string Label => SettingsStrings . notificationOptionSound ;
31
33
@@ -35,18 +37,33 @@ public void NotifyDefaultChanged(MMDevice audioDevice)
35
37
{
36
38
if ( audioDevice . DataFlow != DataFlow . Render )
37
39
return ;
38
-
39
- Task . Factory . StartNew ( ( ) =>
40
+
41
+ _cancellationTokenSource ? . Cancel ( ) ;
42
+ _cancellationTokenSource ? . Dispose ( ) ;
43
+ _cancellationTokenSource = new CancellationTokenSource ( ) ;
44
+ Task . Factory . StartNew ( async ( ) =>
40
45
{
41
- using var memoryStreamedSound = GetStreamCopy ( ) ;
42
- using var output = new WasapiOut ( audioDevice , AudioClientShareMode . Shared , true , 10 ) ;
43
- output . Init ( new WaveFileReader ( memoryStreamedSound ) ) ;
44
- output . Play ( ) ;
45
- while ( output . PlaybackState == PlaybackState . Playing )
46
+ try
47
+ {
48
+ using var cts = CancellationTokenSource . CreateLinkedTokenSource ( _cancellationTokenSource . Token ) ;
49
+ using var player = new WasapiOut ( audioDevice , AudioClientShareMode . Shared , true , 200 ) ;
50
+ await using var memoryStreamedSound = GetStreamCopy ( ) ;
51
+ await using var waveStream = new WaveFileReader ( memoryStreamedSound ) ;
52
+ player . Init ( waveStream ) ;
53
+
54
+ player . PlaybackStopped += ( _ , _ ) => cts . CancelAfter ( TimeSpan . FromMilliseconds ( 750 ) ) ;
55
+ player . Play ( ) ;
56
+ await Task . Delay ( - 1 , cts . Token ) ;
57
+ }
58
+ catch ( TaskCanceledException )
59
+ {
60
+ //Ignored
61
+ }
62
+ catch ( Exception e )
46
63
{
47
- Thread . Sleep ( 500 ) ;
64
+ Log . Warning ( e , "Issue while playing default sound" ) ;
48
65
}
49
- } ) ;
66
+ } , _cancellationTokenSource . Token ) ;
50
67
}
51
68
52
69
public void OnSoundChanged ( CachedSound newSound )
0 commit comments