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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
|
//
// ViewController.m
// Video Tuneup
//
// Created by Brian Jordan on 3/27/12.
// Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//
#import "ViewController.h"
#import "PlayerView.h"
#import "SimpleEditor.h"
#import "AssetsViewController.h"
#import "WebserviceCommunicator.h"
// Define this constant for the key-value observation context.
static const NSString *ItemStatusContext;
@implementation ViewController
@synthesize player, playerItem, playerView, playButton, pauseButton, rewindButton, editor, videoNavBar, exportStatus,
mScrubber, mediaLibraryButton, mediaLibraryPopover, exportButton, defaultHelpView;
@synthesize internetRequestButton;
#pragma mark - Video playback
- (void)syncUI {
NSLog(@"syncUI");
if ((player.currentItem != nil) &&
([player.currentItem status] == AVPlayerItemStatusReadyToPlay &&
CMTimeCompare([player.currentItem duration], kCMTimeZero) != 0)) {
playButton.enabled = YES;
NSLog(@"Enabling play button");
}
else {
playButton.enabled = NO;
NSLog(@"Play button disabled");
}
}
- (void)refreshEditor {
NSLog(@"Refreshing editor");
// Update editor assets
if (asset)
self.editor.video = asset;
if (songAsset)
self.editor.song = songAsset;
// Remove old player
[self.player pause];
// Build composition for playback
[self.editor buildNewCompositionForPlayback:YES];
// Initialize editor's player
self.playerItem = self.editor.playerItem;
[playerItem addObserver:self forKeyPath:@"status"
options:0 context:&ItemStatusContext];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:self.playerItem];
self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
[playerView setPlayer:self.player];
[self play:nil];
}
- (void)loadAssetFromFile:(NSURL*)fileURL {
asset = [AVURLAsset URLAssetWithURL:fileURL options:nil];
NSLog(@"Asset duration is %f", CMTimeGetSeconds([asset duration]));
NSString *tracksKey = @"tracks";
[asset loadValuesAsynchronouslyForKeys:[NSArray arrayWithObject:tracksKey] completionHandler:
^{
NSLog(@"Handler block reached");
// Completion handler block.
dispatch_async(dispatch_get_main_queue(),
^{
NSError *error = nil;
AVKeyValueStatus status = [asset statusOfValueForKey:tracksKey error:&error];
if (status == AVKeyValueStatusLoaded) {
[self refreshEditor];
// File has loaded into player
NSLog(@"File loaded!");
NSLog(@"Asset duration is %f", CMTimeGetSeconds([asset duration]));
}
else {
// You should deal with the error appropriately.
NSLog(@"The asset's tracks were not loaded:\n%@", [error localizedDescription]);
}
});
}];
}
- (IBAction)loadDefaultAssetFromFile:sender {
NSLog(@"Loading asset.");
NSURL *fileURL = [[NSBundle mainBundle]
URLForResource:@"sample_iPod" withExtension:@"m4v"];
[self loadAssetFromFile:fileURL];
}
- (IBAction)loadDefaultAudioFromFile:(id)sender {
NSURL *songFileURL = [[NSBundle mainBundle]
URLForResource:@"song" withExtension:@"mp3"];
[self loadAudioFromFile:songFileURL];
}
- (IBAction)loadAudioFromFile:(NSURL *)songFileURL {
songAsset = [AVURLAsset URLAssetWithURL:songFileURL options:nil];
NSLog(@"Song asset duration is %f", CMTimeGetSeconds([songAsset duration]));
if(CMTimeGetSeconds([songAsset duration]) == 0){
[internetRequestButton setTitle:@"Internet Tune-up (failed)" forState:UIControlStateNormal];
return;
}
NSLog(@"Refreshing editor");
[self refreshEditor];
}
#pragma mark -
#pragma mark Audio picker
- (IBAction)showMediaPicker:(id)sender
{
MPMediaPickerController *mediaPicker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
mediaPicker.wantsFullScreenLayout = NO;
mediaPicker.delegate = self;
mediaPicker.allowsPickingMultipleItems = NO;
mediaPicker.prompt = @"Select songs to play";
[self presentModalViewController:mediaPicker animated:YES];
// [mediaPicker release];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection {
if (mediaItemCollection) {
NSLog(@"Got media item");
// NSLog(@"%@",[[[mediaItemCollection items] objectAtIndex:0]valueForKey:MPMediaItemPropertyTitle]);
NSURL *url = [[[mediaItemCollection items] objectAtIndex:0] valueForProperty:MPMediaItemPropertyAssetURL];
// NSLog(@"%@", url);
[self loadAudioFromFile:url];
} else {NSLog(@"Didn't get media item!");}
[self dismissModalViewControllerAnimated:YES];
}
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker
{
[self dismissModalViewControllerAnimated: YES];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object
change:(NSDictionary *)change context:(void *)context {
if (context == &ItemStatusContext) {
// Have to dispatch to main thread queue for UI operations
dispatch_async(dispatch_get_main_queue(),
^{
[self syncUI];
});
return;
}
[super observeValueForKeyPath:keyPath ofObject:object
change:change context:context];
return;
}
- (IBAction)play:(id)sender {
if(player.rate == 0 && (player.currentItem != nil) &&
([player.currentItem status] == AVPlayerItemStatusReadyToPlay &&
CMTimeCompare([player.currentItem duration], kCMTimeZero) != 0)) { // Paused
NSLog(@"Playing item");
[player play];
[self initScrubberTimer];
[self.videoNavBar setItems:[NSArray
arrayWithObjects:[self.videoNavBar.items objectAtIndex:0],
[self.videoNavBar.items objectAtIndex:1],
[self.videoNavBar.items objectAtIndex:2],
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPause target:self action:@selector(play:)],[self.videoNavBar.items objectAtIndex:4],[self.videoNavBar.items objectAtIndex:5],nil] animated:NO];
} else {
[player pause];
[self.videoNavBar setItems:[NSArray arrayWithObjects:[self.videoNavBar.items objectAtIndex:0],
[self.videoNavBar.items objectAtIndex:1],
[self.videoNavBar.items objectAtIndex:2],
[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemPlay target:self action:@selector(play:)],[self.videoNavBar.items objectAtIndex:4],
[self.videoNavBar.items objectAtIndex:5], nil] animated:NO];
}
}
- (IBAction)pause:(id)sender {
NSLog(@"Pausing...");
[player pause];
}
- (IBAction)rewind:(id)sender {
[player seekToTime:kCMTimeZero];
}
// Handle scrubbing
// Based on sample code from http://developer.apple.com/library/ios/#samplecode/AVPlayerDemo/Listings/Classes_AVPlayerDemoPlaybackViewController_m.html#//apple_ref/doc/uid/DTS40010101-Classes_AVPlayerDemoPlaybackViewController_m-DontLinkElementID_8
#pragma mark -
#pragma mark Movie scrubber control
/* ---------------------------------------------------------
** Methods to handle manipulation of the movie scrubber control
** ------------------------------------------------------- */
- (CMTime)playerItemDuration
{
return [playerItem duration];
}
/* Requests invocation of a given block during media playback to update the movie scrubber control. */
-(void)initScrubberTimer
{
double interval = .1f;
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration))
{
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration))
{
CGFloat width = CGRectGetWidth([mScrubber bounds]);
interval = 0.5f * duration / width;
}
/* Update the scrubber during normal playback. */
mTimeObserver = [player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(interval, NSEC_PER_SEC)
queue:NULL /* If you pass NULL, the main queue is used. */
usingBlock:^(CMTime time)
{
[self syncScrubber];
}];
}
/* Set the scrubber based on the player current time. */
- (void)syncScrubber
{
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration))
{
mScrubber.minimumValue = 0.0;
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration))
{
float minValue = [mScrubber minimumValue];
float maxValue = [mScrubber maximumValue];
double time = CMTimeGetSeconds([player currentTime]);
[mScrubber setValue:(maxValue - minValue) * time / duration + minValue];
}
}
/* The user is dragging the movie controller thumb to scrub through the movie. */
- (IBAction)beginScrubbing:(id)sender
{
mRestoreAfterScrubbingRate = [player rate];
[player setRate:0.f];
/* Remove previous timer. */
// [self removePlayerTimeObserver];
}
/* Set the player current time to match the scrubber position. */
- (IBAction)scrub:(id)sender
{
if ([sender isKindOfClass:[UISlider class]])
{
UISlider* slider = sender;
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration)) {
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration))
{
float minValue = [slider minimumValue];
float maxValue = [slider maximumValue];
float value = [slider value];
double time = duration * (value - minValue) / (maxValue - minValue);
[player seekToTime:CMTimeMakeWithSeconds(time, NSEC_PER_SEC)];
}
}
}
/* The user has released the movie thumb control to stop scrubbing through the movie. */
- (IBAction)endScrubbing:(id)sender
{
if (!mTimeObserver)
{
CMTime playerDuration = [self playerItemDuration];
if (CMTIME_IS_INVALID(playerDuration))
{
return;
}
double duration = CMTimeGetSeconds(playerDuration);
if (isfinite(duration))
{
CGFloat width = CGRectGetWidth([mScrubber bounds]);
double tolerance = 0.5f * duration / width;
mTimeObserver = [player addPeriodicTimeObserverForInterval:CMTimeMakeWithSeconds(tolerance, NSEC_PER_SEC) queue:NULL usingBlock:
^(CMTime time)
{
[self syncScrubber];
}];
}
}
if (mRestoreAfterScrubbingRate)
{
[player setRate:mRestoreAfterScrubbingRate];
mRestoreAfterScrubbingRate = 0.f;
}
}
- (BOOL)isScrubbing
{
return mRestoreAfterScrubbingRate != 0.f;
}
-(void)enableScrubber
{
self.mScrubber.enabled = YES;
}
-(void)disableScrubber
{
self.mScrubber.enabled = NO;
}
- (IBAction)exportToCameraRoll:(id)sender {
[exportButton setTitle:@"Exporting..." forState:UIControlStateNormal];
[exportButton setEnabled:NO];
NSLog(@"Editing...");
NSLog(@"Put clips in. Build.");
AVAssetExportSession *session = [self.editor assetExportSessionWithPreset:AVAssetExportPresetHighestQuality];
NSLog(@"Session");
NSLog(@"begin export");
NSString *filePath = nil;
NSUInteger count = 0;
do {
NSLog(@"Filepath");
filePath = NSTemporaryDirectory();
NSString *numberString = count > 0 ? [NSString stringWithFormat:@"-%i", count] : @"";
filePath = [filePath stringByAppendingPathComponent:[NSString stringWithFormat:@"Output-%@.mov", numberString]];
count++;
} while ([[NSFileManager defaultManager] fileExistsAtPath:filePath]);
NSLog(@"Setting stuff.");
session.outputURL = [NSURL fileURLWithPath:filePath];
session.outputFileType = AVFileTypeQuickTimeMovie;
[session exportAsynchronouslyWithCompletionHandler:^{
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Finished exporting.");
[self exportDidFinish:session];
});
}];
}
- (void)exportDidFinish:(AVAssetExportSession *)session {
NSLog(@"Finished export, attempting photo album");
NSURL *outputURL = session.outputURL;
// _exporting = NO;
// NSIndexPath *exportCellIndexPath = [NSIndexPath indexPathForRow:2 inSection:kProjectSection];
// ExportCell *cell = (ExportCell*)[self.tableView cellForRowAtIndexPath:exportCellIndexPath];
// cell.progressView.progress = 1.0;
// [cell setProgressViewHidden:YES animated:YES];
// [self updateCell:cell forRowAtIndexPath:exportCellIndexPath];
ALAssetsLibrary *library = [[ALAssetsLibrary alloc] init];
if ([library videoAtPathIsCompatibleWithSavedPhotosAlbum:outputURL]) {
[library writeVideoAtPathToSavedPhotosAlbum:outputURL
completionBlock:^(NSURL *assetURL, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(@"writeVideoToAssestsLibrary failed: %@", error);
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[error localizedDescription]
message:[error localizedRecoverySuggestion]
delegate:nil cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[alertView show];
// [alertView release];
[exportStatus setText:@"Camera Roll Export Error"];
[exportButton setEnabled:YES];
}
else {
NSLog(@"Completed photo album add");
[exportButton setTitle:@"Share to Camera Roll" forState:UIControlStateNormal];
[exportButton setEnabled:YES];
[exportStatus setTextColor:[UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:255.0]];
[exportStatus setText:@"Saved!"];
// [exportStatus setBackgroundColor:[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"argyle.png"]]];
// [exportStatus setBackgroundColor:[UIColor colorWithRed:0.0 green:200.0 blue:0.0 alpha:255.0]];
[self performSelector:@selector(hideCameraRollText) withObject:nil afterDelay:5.0];
}
});
}];
} else {
NSLog(@"Video format is not compatible with saved photos album.");
[exportStatus setTextColor:[UIColor colorWithRed:255.0 green:255.0 blue:255.0 alpha:255.0]];
[exportStatus setText:@"Select a video first."];
[exportStatus setBackgroundColor:[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"argyle.png"]]];
[self performSelector:@selector(hideCameraRollText) withObject:nil afterDelay:5.0];
}
}
- (void)hideCameraRollText { [exportStatus setText: @""]; [exportStatus setBackgroundColor:[UIColor colorWithRed:0.0 green:0.0 blue:0.0 alpha:0.0]];}
- (void)playerItemDidReachEnd:(NSNotification *)notification {
[player seekToTime:kCMTimeZero];
[player play]; // loop player. If not doing this, set button to pause
}
#pragma mark - Media Library
- (IBAction)showMediaLibrary:(id)sender {
// http://stackoverflow.com/questions/2469523/mpmediapickercontroller-for-selecting-video-files#answer-3212470
UIButton *theButton = (UIButton *)sender;
AssetsViewController *avc = [[AssetsViewController alloc] initWithStyle:UITableViewStylePlain];
[avc setParentViewController:self];
mediaLibraryPopover = [[UIPopoverController alloc] initWithContentViewController:avc];
// [mediaLibraryPopover setPopoverContentSize:<#(CGSize)#>// Change size of popover so that it doesn't take up the whole height
[self.mediaLibraryPopover presentPopoverFromRect:[theButton bounds] inView:theButton permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
}
#pragma mark - Networking
- (IBAction)sendMixRequest:(id)sender {
WebserviceCommunicator *com = [[WebserviceCommunicator alloc] init];
NSURL *songFileURL = [[NSBundle mainBundle] URLForResource:@"song" withExtension:@"mp3"];
[com setParentController:self];
[com mixMusic:songFileURL];
[internetRequestButton setTitle:@"Attempting..." forState:UIControlStateNormal];
}
#pragma mark - View controller boilerplate
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
#pragma mark - View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
self.view.backgroundColor = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"hixs_pattern_evolution.png"]];
[defaultHelpView setBackgroundColor:[[UIColor alloc] initWithPatternImage:[UIImage imageNamed:@"noisy tile.png"]]];
NSLog(@"viewDidLoad");
// Initialize editor
self.editor = [[SimpleEditor alloc] init];
[self refreshEditor]; // Generate composition
// Sync video player controls
NSLog(@"syncUI");
[self syncUI];
// Register with the notification center after creating the player item.
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:@selector(playerItemDidReachEnd:)
name:AVPlayerItemDidPlayToEndTimeNotification
object:[player currentItem]];
NSLog(@"registered");
}
- (void)viewDidUnload {
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
}
- (void)viewDidAppear:(BOOL)animated {
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
if ([[UIDevice currentDevice] userInterfaceIdiom] == UIUserInterfaceIdiomPhone) {
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
} else {
return YES;
}
}
- (void)toggleHelpView {
if (! [defaultHelpView isHidden]) {
[playerView setHidden:NO];
[videoNavBar setHidden:NO];
[defaultHelpView setHidden:YES];
}
else {
[defaultHelpView setHidden:NO];
[playerView setHidden:YES];
[videoNavBar setHidden:YES];
}
}
@end
|