This repository has been archived by the owner on Apr 29, 2024. It is now read-only.
/
MainViewController.cs
354 lines (280 loc) · 9.34 KB
/
MainViewController.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
using System;
using UIKit;
using Foundation;
using AVFoundation;
using AssetsLibrary;
using System.Linq;
using CoreMedia;
using CoreFoundation;
using System.Threading;
namespace AudioTapProcessor
{
[Register ("MainViewController")]
public class MainViewController : UIViewController
{
static NSUrl movieUrl;
NSObject playerTimeObserver;
NSObject playerItemDidPlayToEndTimeObserver;
AVPlayer player;
public AVPlayer Player {
get {
return player = player ?? new AVPlayer (movieUrl);
}
}
bool IsStopped {
get {
return Player.Rate == 0;
}
}
AudioTapProcessor audioTapProcessor;
public AudioTapProcessor AudioTapProcessor {
get {
return audioTapProcessor = audioTapProcessor ?? CreateTapProcessor ();
}
}
[Outlet ("playerView")]
PlayerView PlayerView { get; set; }
[Outlet ("leftChannelVolumeUnitMeterView")]
VolumeUnitMeterView LeftChannelVolumeUnitMeterView { get; set; }
[Outlet ("rightChannelVolumeUnitMeterView")]
VolumeUnitMeterView RightChannelVolumeUnitMeterView { get; set; }
[Outlet ("playPauseButton")]
UIButton PlayPauseButton { get; set; }
[Outlet ("elapsedTimeLabel")]
UILabel ElapsedTimeLabel { get; set; }
[Outlet ("currentTimeSlider")]
UISlider CurrentTimeSlider { get; set; }
[Outlet ("remainingTimeLabel")]
UILabel RemainingTimeLabel { get; set; }
[Outlet ("settingsPopoverButton")]
UIButton SettingsPopoverButton { get; set; }
static MainViewController ()
{
movieUrl = fetchMovieUrl ();
}
public MainViewController (IntPtr handle)
: base (handle)
{
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
// Attach player to player view.
PlayerView.Player = Player;
// Disable play pause button and current time slider (until player is ready to play).
PlayPauseButton.Enabled = false;
CurrentTimeSlider.Enabled = false;
// Disable settings popover button (until audio tap is created).
SettingsPopoverButton.Enabled = false;
// Start observing player's status.
// TODO: https://trello.com/c/SeE2FBoN
Player.AddObserver (this, "status", NSKeyValueObservingOptions.Initial | NSKeyValueObservingOptions.New, IntPtr.Zero);
// Add player item did play to end time observer.
AVPlayerItem.Notifications.ObserveDidPlayToEndTime (DidPlayToEndTime);
}
void DidPlayToEndTime (object sender, NSNotificationEventArgs args)
{
if (args.Notification.Object != Player.CurrentItem)
return;
// Update play pause button.
PlayPauseButton.SetImage (UIImage.FromBundle ("PlayButton"), UIControlState.Normal);
}
public override void PrepareForSegue (UIStoryboardSegue segue, NSObject sender)
{
base.PrepareForSegue (segue, sender);
if (segue.Identifier == "ShowSettingsSegue")
SetupSettingsViewController (segue);
}
void SetupSettingsViewController (UIStoryboardSegue segue)
{
// Setup settings view controller before it is shown.
UIViewController topViewController = ((UINavigationController)segue.DestinationViewController).TopViewController;
var settingsViewController = (SettingsViewController)topViewController;
settingsViewController.Controller = this;
settingsViewController.EnabledSwitchValue = AudioTapProcessor.IsBandpassFilterEnabled;
settingsViewController.CenterFrequencySliderValue = AudioTapProcessor.CenterFrequency;
settingsViewController.BandwidthSliderValue = AudioTapProcessor.Bandwidth;
}
// TODO: https://trello.com/c/SeE2FBoN
public override void ObserveValue (NSString keyPath, NSObject ofObject, NSDictionary change, IntPtr context)
{
if (FetchStatus (change) == AVPlayerStatus.ReadyToPlay)
OnReadyToPlay ();
}
AVPlayerStatus FetchStatus (NSDictionary change)
{
var ch = new NSObservedChange (change);
var newValue = (NSNumber)ch.NewValue;
return newValue == null ? AVPlayerStatus.Unknown : (AVPlayerStatus)newValue.Int32Value;
}
void OnReadyToPlay ()
{
CMTime duration = Player.CurrentItem.Duration;
ResetUpdateTimeIndicators (duration);
// Add time observer for current time slider and label.
playerTimeObserver = Player.AddPeriodicTimeObserver (new CMTime (1, 1), DispatchQueue.MainQueue, time =>
UpdateTimeIndicators (time, duration)
);
// Add audio mix with audio tap processor to current player item.
TryAddAudioMix ();
// Enable play pause button and current time slider.
PlayPauseButton.Enabled = true;
CurrentTimeSlider.Enabled = true;
}
void ResetUpdateTimeIndicators (CMTime duration)
{
ElapsedTimeLabel.Text = BuildTimeString (CMTime.Zero);
CurrentTimeSlider.Value = 0;
RemainingTimeLabel.Text = BuildTimeString (duration, "-");
}
void UpdateTimeIndicators (CMTime time, CMTime duration)
{
ElapsedTimeLabel.Text = BuildTimeString (time);
CurrentTimeSlider.Value = (float)(time.Seconds / duration.Seconds);
RemainingTimeLabel.Text = BuildTimeString (duration - time, "-");
}
void TryAddAudioMix ()
{
AVAudioMix audioMix = AudioTapProcessor.AudioMix;
if (audioMix == null)
return;
// Add audio mix with first audio track.
Player.CurrentItem.AudioMix = audioMix;
// Enable settings popover button.
SettingsPopoverButton.Enabled = true;
}
#region Actions
[Export ("togglePlayPause:")]
void TogglePlayPause (NSObject sender)
{
AssertPlayerNotNull ();
if (IsStopped) {
// Play from beginning when playhead is at end.
TryResetPlayhead ();
StartPlayback ();
} else {
StopPlayback ();
}
}
void AssertPlayerNotNull ()
{
if (Player == null)
throw new InvalidOperationException ("Player is null");
}
void TryResetPlayhead ()
{
AVPlayerItem cItem = Player.CurrentItem;
if (cItem.CurrentTime >= cItem.Duration)
cItem.Seek (CMTime.Zero, CMTime.Zero, CMTime.Zero);
}
void StartPlayback ()
{
player.Rate = 1;
PlayPauseButton.SetImage (UIImage.FromBundle ("PauseButton"), UIControlState.Normal);
}
void StopPlayback ()
{
Player.Rate = 0;
PlayPauseButton.SetImage (UIImage.FromBundle ("PlayButton"), UIControlState.Normal);
}
[Export ("seekToTime:")]
void SeekToTime (UISlider slider)
{
AssertPlayerNotNull ();
Player.Seek (Player.CurrentItem.Duration * slider.Value, CMTime.Zero, CMTime.Zero);
}
#endregion
public void OnNewLeftRightChanelValue (AudioTapProcessor processor, float lChannelValue, float rChannelValue)
{
// Update left and right channel volume unit meter.
LeftChannelVolumeUnitMeterView.Value = lChannelValue;
RightChannelVolumeUnitMeterView.Value = rChannelValue;
}
#region SettingsViewController callbacks
public void DidUpdateEnabledSwitchValue (bool enable)
{
// Forward value to audio tap processor.
AudioTapProcessor.IsBandpassFilterEnabled = enable;
}
public void DidUpdateCenterFrequencySliderValue (float sliderValue)
{
// Forward value to audio tap processor.
AudioTapProcessor.CenterFrequency = sliderValue;
}
public void DidUpdateBandwidthSliderValue (float sliderValue)
{
// Forward value to audio tap processor.
AudioTapProcessor.Bandwidth = sliderValue;
}
#endregion
static NSUrl fetchMovieUrl ()
{
NSUrl movieURL = null;
var waitHandle = new AutoResetEvent (false);
ThreadPool.QueueUserWorkItem (_ => {
ALAssetsLibrary assetsLibrary = new ALAssetsLibrary ();
assetsLibrary.Enumerate (ALAssetsGroupType.All, (ALAssetsGroup group, ref bool stop) => {
if (group == null) {
waitHandle.Set ();
return;
}
NSDate latest = NSDate.FromTimeIntervalSince1970(0);
group.Enumerate ((ALAsset result, nint index, ref bool stopGroup) => {
if(result == null || result.AssetType != ALAssetType.Video)
return;
NSUrl url = result.DefaultRepresentation.Url;
if (url == null)
return;
var diff = result.Date.SecondsSinceReferenceDate - latest.SecondsSinceReferenceDate;
if(diff > 0) {
latest = result.Date;
movieURL = url;
}
});
stop = movieURL != null;
}, (error) => {
waitHandle.Set ();
});
});
waitHandle.WaitOne ();
if (movieURL == null) {
UIAlertView alertView = new UIAlertView (null, "Could not find any movies in assets library to use as sample content.", null, "OK", null);
alertView.Show ();
}
return movieURL;
}
AudioTapProcessor CreateTapProcessor ()
{
AudioTapProcessor processor = null;
AVAssetTrack firstAudioAssetTrack = FetchFirstAudioTrack (Player);
if (firstAudioAssetTrack != null) {
processor = new AudioTapProcessor (firstAudioAssetTrack);
processor.Controller = this;
}
return processor;
}
protected override void Dispose (bool disposing)
{
playerTimeObserver.Dispose ();
playerItemDidPlayToEndTimeObserver.Dispose ();
base.Dispose (disposing);
}
static AVAssetTrack FetchFirstAudioTrack (AVPlayer player)
{
AVAssetTrack[] tracks = player.CurrentItem.Asset.Tracks;
AVAssetTrack firstAudioTrack = tracks.FirstOrDefault (t => t.MediaType == AVMediaType.Audio);
return firstAudioTrack;
}
static string BuildTimeString (CMTime time, string sign = null)
{
sign = sign ?? string.Empty;
var seconds = Math.Round (time.Seconds);
int hh = (int)Math.Floor (seconds / 3600);
int mm = (int)Math.Floor ((seconds - hh * 3600) / 60);
int ss = (int)seconds % 60;
return hh > 0
? string.Format ("{0}{1:00}:{2:00}:{3:00}", sign, hh, mm, ss)
: string.Format ("{0}{1:00}:{2:00}", sign, mm, ss);
}
}
}