Skip to content

Commit

Permalink
fix(Banner::Sound): Fix crash when setting a sound for the banner.
Browse files Browse the repository at this point in the history
Fixes #730
Fixes SOUNDSWITCH-6N
  • Loading branch information
Belphemur committed Aug 28, 2021
1 parent 177b08d commit d8fcf3c
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 9 deletions.
18 changes: 13 additions & 5 deletions SoundSwitch/Framework/Banner/BannerForm.cs
Original file line number Diff line number Diff line change
Expand Up @@ -80,7 +80,7 @@ internal void SetData(BannerData data)
_currentData = data;
if (_timerHide == null)
{
_timerHide = new Timer {Interval = 3000};
_timerHide = new Timer { Interval = 3000 };
_timerHide.Tick += TimerHide_Tick;
}
else
Expand All @@ -91,10 +91,10 @@ internal void SetData(BannerData data)
if (data.Image != null)
pbxLogo.Image = data.Image;

DestroySound();

if (data.SoundFile != null)
{
DestroySound();
PrepareSound(data);
}

Expand All @@ -115,16 +115,24 @@ private void PrepareSound(BannerData data)
{
Task.Factory.StartNew(async () =>
{

try
{
using var cancellationTokenSource = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token);
using var semaphore = new SemaphoreSlim(0);
using var player = data.CurrentDevice == null ? new WasapiOut() : new WasapiOut(data.CurrentDevice, AudioClientShareMode.Shared, true, 200);
await using var waveStream = new CachedSoundWaveStream(data.SoundFile);
player.Init(waveStream);

player.PlaybackStopped += (_, _) => cancellationTokenSource.CancelAfter(TimeSpan.FromMilliseconds(750));
player.PlaybackStopped += (_, _) =>
{
if (_cancellationTokenSource.Token.IsCancellationRequested)
{
return;
}
semaphore.Release();
};
player.Play();
await Task.Delay(-1, cancellationTokenSource.Token);
await semaphore.WaitAsync(_cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,15 +45,21 @@ public void NotifyDefaultChanged(MMDevice audioDevice)
{
try
{
using var cts = CancellationTokenSource.CreateLinkedTokenSource(_cancellationTokenSource.Token);
using var semaphore = new SemaphoreSlim(0);
using var player = new WasapiOut(audioDevice, AudioClientShareMode.Shared, true, 200);
await using var memoryStreamedSound = GetStreamCopy();
await using var waveStream = new WaveFileReader(memoryStreamedSound);
player.Init(waveStream);

player.PlaybackStopped += (_, _) => cts.CancelAfter(TimeSpan.FromMilliseconds(750));
player.Play();
await Task.Delay(-1, cts.Token);
player.PlaybackStopped += (_, _) =>
{
if (_cancellationTokenSource.Token.IsCancellationRequested)
{
return;
}
semaphore.Release();
}; player.Play();
await semaphore.WaitAsync(_cancellationTokenSource.Token);
}
catch (TaskCanceledException)
{
Expand Down

0 comments on commit d8fcf3c

Please sign in to comment.