-
Notifications
You must be signed in to change notification settings - Fork 53
/
SimpleAudioPlayerImplementation.cs
287 lines (240 loc) · 7.5 KB
/
SimpleAudioPlayerImplementation.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
using Android.Content.Res;
using System;
using System.IO;
using Uri = Android.Net.Uri;
namespace Plugin.SimpleAudioPlayer
{
/// <summary>
/// Implementation for Feature
/// </summary>
[Android.Runtime.Preserve(AllMembers = true)]
public class SimpleAudioPlayerImplementation : ISimpleAudioPlayer
{
///<Summary>
/// Raised when audio playback completes successfully
///</Summary>
public event EventHandler PlaybackEnded;
Android.Media.MediaPlayer player;
static int index = 0;
///<Summary>
/// Length of audio in seconds
///</Summary>
public double Duration => player == null ? 0 : player.Duration / 1000.0;
///<Summary>
/// Current position of audio playback in seconds
///</Summary>
public double CurrentPosition => player == null ? 0 : (player.CurrentPosition) / 1000.0;
///<Summary>
/// Playback volume (0 to 1)
///</Summary>
public double Volume
{
get =>_volume;
set
{
SetVolume(_volume = value, Balance);
}
}
double _volume = 0.5;
///<Summary>
/// Balance left/right: -1 is 100% left : 0% right, 1 is 100% right : 0% left, 0 is equal volume left/right
///</Summary>
public double Balance
{
get => _balance;
set
{
SetVolume(Volume, _balance = value);
}
}
double _balance = 0;
///<Summary>
/// Indicates if the currently loaded audio file is playing
///</Summary>
public bool IsPlaying => player != null && player.IsPlaying;
///<Summary>
/// Continously repeats the currently playing sound
///</Summary>
public bool Loop
{
get => _loop;
set { _loop = value; if (player != null) player.Looping = _loop; }
}
bool _loop;
///<Summary>
/// Indicates if the position of the loaded audio file can be updated
///</Summary>
public bool CanSeek => player != null;
string path;
/// <summary>
/// Instantiates a new SimpleAudioPlayer
/// </summary>
public SimpleAudioPlayerImplementation()
{
player = new Android.Media.MediaPlayer() { Looping = Loop };
player.Completion += OnPlaybackEnded;
}
///<Summary>
/// Load wav or mp3 audio file as a stream
///</Summary>
public bool Load(Stream audioStream)
{
player.Reset();
DeleteFile(path);
//cache to the file system
path = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), $"cache{index++}.wav");
var fileStream = File.Create(path);
audioStream.CopyTo(fileStream);
fileStream.Close();
try
{
player.SetDataSource(path);
}
catch
{
try
{
var context = Android.App.Application.Context;
player?.SetDataSource(context, Uri.Parse(Uri.Encode(path)));
}
catch
{
return false;
}
}
return PreparePlayer();
}
///<Summary>
/// Load wav or mp3 audio file from the iOS Resources folder
///</Summary>
public bool Load(string fileName)
{
player.Reset();
AssetFileDescriptor afd = Android.App.Application.Context.Assets.OpenFd(fileName);
player?.SetDataSource(afd.FileDescriptor, afd.StartOffset, afd.Length);
return PreparePlayer();
}
bool PreparePlayer()
{
player?.Prepare();
return player != null;
}
void DeletePlayer()
{
Stop();
if (player != null)
{
player.Completion -= OnPlaybackEnded;
player.Release();
player.Dispose();
player = null;
}
DeleteFile(path);
path = string.Empty;
}
void DeleteFile(string path)
{
if (string.IsNullOrWhiteSpace(path) == false)
{
try
{
File.Delete(path);
}
catch
{
}
}
}
///<Summary>
/// Begin playback or resume if paused
///</Summary>
public void Play()
{
if (player == null)
return;
if (IsPlaying)
{
Pause();
Seek(0);
}
player.Start();
}
///<Summary>
/// Stop playack and set the current position to the beginning
///</Summary>
public void Stop()
{
if(!IsPlaying)
return;
Pause();
Seek(0);
PlaybackEnded?.Invoke(this, EventArgs.Empty);
}
///<Summary>
/// Pause playback if playing (does not resume)
///</Summary>
public void Pause()
{
player?.Pause();
}
///<Summary>
/// Set the current playback position (in seconds)
///</Summary>
public void Seek(double position)
{
if(CanSeek)
player?.SeekTo((int)(position * 1000D));
}
///<Summary>
/// Sets the playback volume as a double between 0 and 1
/// Sets both left and right channels
///</Summary>
void SetVolume(double volume, double balance)
{
volume = Math.Max(0, volume);
volume = Math.Min(1, volume);
balance = Math.Max(-1, balance);
balance = Math.Min(1, balance);
// Using the "constant power pan rule." See: http://www.rs-met.com/documents/tutorials/PanRules.pdf
var left = Math.Cos((Math.PI * (balance + 1)) / 4) * volume;
var right = Math.Sin((Math.PI * (balance + 1)) / 4) * volume;
player?.SetVolume((float)left, (float)right);
}
void OnPlaybackEnded(object sender, EventArgs e)
{
PlaybackEnded?.Invoke(sender, e);
//this improves stability on older devices but has minor performance impact
// We need to check whether the player is null or not as the user might have dipsosed it in an event handler to PlaybackEnded above.
if (player != null && Android.OS.Build.VERSION.SdkInt < Android.OS.BuildVersionCodes.M)
{
player.SeekTo(0);
player.Stop();
player.Prepare();
}
}
bool isDisposed = false;
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
protected virtual void Dispose(bool disposing)
{
if (isDisposed || player == null)
return;
if (disposing)
DeletePlayer();
isDisposed = true;
}
~SimpleAudioPlayerImplementation()
{
Dispose(false);
}
///<Summary>
/// Dispose SimpleAudioPlayer and release resources
///</Summary>
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
}
}