-
Notifications
You must be signed in to change notification settings - Fork 17
/
AudioOut.cs
73 lines (61 loc) · 2.03 KB
/
AudioOut.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
using System;
using System.IO;
using System.Media;
using System.Resources;
using System.Windows.Media;
using NAudio.Wave;
namespace GoogleAssistantWindows
{
public class AudioOut
{
public delegate void AudioPlaybackStateChangeDelegate(bool started);
public event AudioPlaybackStateChangeDelegate OnAudioPlaybackStateChanged;
private static readonly WaveFormat WaveFormat = new WaveFormat(Const.SampleRateHz, 1);
private WaveOut _waveOut;
private MemoryStream _ms;
private RawSourceWaveStream _waveStream;
public void AddBytesToPlay(byte[] bytes)
{
if (_waveOut == null)
{
_waveOut = new WaveOut();
_waveOut.PlaybackStopped += (sender, args) =>
{
_waveStream.Dispose();
_ms.Dispose();
_ms = null;
OnAudioPlaybackStateChanged?.Invoke(false);
};
}
if (_ms == null)
_ms = new MemoryStream();
_ms.Write(bytes, 0, bytes.Length);
}
public void Play()
{
if (_ms != null && _ms.Length > 0)
{
_ms.Position = 0;
_waveStream = new RawSourceWaveStream(_ms, WaveFormat);
_waveOut.Init(_waveStream);
_waveOut.Play();
OnAudioPlaybackStateChanged?.Invoke(true);
}
}
public void PlayNotification()
{
PlayNotification(AppDomain.CurrentDomain.BaseDirectory + "Resources\\positive.wav");
}
public void PlayNegativeNotification()
{
PlayNotification(AppDomain.CurrentDomain.BaseDirectory + "Resources\\negative.wav");
}
public void PlayNotification(string notificationFile)
{
using (var soundPlayer = new SoundPlayer(notificationFile))
{
soundPlayer.Play();
}
}
}
}