Skip to content

Commit 08ca605

Browse files
committed
fix(Notification::Sound): Fix issue where sound wasn't played properly.
Fixes SOUNDSWITCH-4Q
1 parent 4faf17a commit 08ca605

File tree

1 file changed

+26
-9
lines changed

1 file changed

+26
-9
lines changed

SoundSwitch/Framework/NotificationManager/Notification/NotificationSound.cs

+26-9
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
using System.Threading.Tasks;
1919
using NAudio.CoreAudioApi;
2020
using NAudio.Wave;
21+
using Serilog;
2122
using SoundSwitch.Framework.Audio;
2223
using SoundSwitch.Framework.NotificationManager.Notification.Configuration;
2324
using SoundSwitch.Localization;
@@ -26,6 +27,7 @@ namespace SoundSwitch.Framework.NotificationManager.Notification
2627
{
2728
public class NotificationSound : INotification
2829
{
30+
private CancellationTokenSource _cancellationTokenSource;
2931
public NotificationTypeEnum TypeEnum => NotificationTypeEnum.SoundNotification;
3032
public string Label => SettingsStrings.notificationOptionSound;
3133

@@ -35,18 +37,33 @@ public void NotifyDefaultChanged(MMDevice audioDevice)
3537
{
3638
if (audioDevice.DataFlow != DataFlow.Render)
3739
return;
38-
39-
Task.Factory.StartNew(() =>
40+
41+
_cancellationTokenSource?.Cancel();
42+
_cancellationTokenSource?.Dispose();
43+
_cancellationTokenSource = new CancellationTokenSource();
44+
Task.Factory.StartNew(async () =>
4045
{
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)
4663
{
47-
Thread.Sleep(500);
64+
Log.Warning(e, "Issue while playing default sound");
4865
}
49-
});
66+
}, _cancellationTokenSource.Token);
5067
}
5168

5269
public void OnSoundChanged(CachedSound newSound)

0 commit comments

Comments
 (0)