How to handle AVPlayerItem observer when app goes foreground from background? - objective-c

I play audio using AVPlayer in the background and foreground from AppDelegate.After adding observer to check the play, a crash occurs when app goes to foreground from background while audio is playing
Crash : "an instance of class AVPlayerItem was deallocated while key value observers were still registered with it"
Many threads explains to remove observer so that we could avoid the crash.But thats in the case of moving to different viewControllers.I want to keep the audio playing in foreground and background.
Can someone help me to solve this?
This is my code:
case AudioLocation:{
audioUrl = [NSURL URLWithString:[responseDictionary
objectForKey:#"result"]];
if(!([[[NSUserDefaults
standardUserDefaults]objectForKey:#"audioURL"] isEqual:
[responseDictionary objectForKey:#"result"]]))
{
playerItem = [AVPlayerItem playerItemWithURL:audioUrl];
player = [AVPlayer playerWithPlayerItem:playerItem];
player = [AVPlayer playerWithURL:audioUrl];
player.automaticallyWaitsToMinimizeStalling = false;
[player.currentItem addObserver:self forKeyPath:#"status"
options:0 context:nil];
[player addObserver:self forKeyPath:#"rate" options:0
context:nil];
[player play];
isPlaying = YES;
}
-(void)observeValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context {
if ([keyPath isEqualToString:#"status"]) {
if (player.status == AVPlayerStatusFailed) {
}
}else if ([keyPath isEqualToString:#"rate"]) {
if (player.rate == 0 && //if player rate dropped to 0
CMTIME_COMPARE_INLINE(player.currentItem.currentTime, >,
kCMTimeZero) &&
CMTIME_COMPARE_INLINE(player.currentItem.currentTime, <,
player.currentItem.duration) &&isPlaying)
[self handleStalled];
}
}
-(void)handleStalled {
NSLog(#"Handle stalled. Available: %lf", [self availableDuration]);
if (player.currentItem.playbackLikelyToKeepUp || //
[self availableDuration] -
CMTimeGetSeconds(player.currentItem.currentTime) > 10.0) {
[player play];
} else {
[self performSelector:#selector(handleStalled) withObject:nil
afterDelay:0.5]; //try again
}
}
- (NSTimeInterval) availableDuration
{
NSArray *loadedTimeRanges = [[player currentItem] loadedTimeRanges];
CMTimeRange timeRange = [[loadedTimeRanges objectAtIndex:0]
CMTimeRangeValue];
Float64 startSeconds = CMTimeGetSeconds(timeRange.start);
Float64 durationSeconds = CMTimeGetSeconds(timeRange.duration);
NSTimeInterval result = startSeconds + durationSeconds;
return result;
}

Related

MPMoviePlayerController does not dismiss view when clicking done?

I use a MPMoviePlayerController to play a video from Internet.
player = [player initWithContentURL:[NSURL URLWithString:videoURL]];
player.view.frame = CGRectMake(0, 0, videoView.frame.size.width, videoView.frame.size.height - 20);
[player setControlStyle:MPMovieControlStyleEmbedded];
player.scalingMode = MPMovieScalingModeAspectFit;
[player prepareToPlay];
player.shouldAutoplay = NO;
[videoView addSubview:player.view];
I notified that after I clicked the full screen button (2-arrows-button), I was navigated to the full size video screen. I couldn't restore down the screen by touching the Done button. I even used NSNotification but can't resolve the problem. Here is the Notification code:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieEventFullscreenHandler:)
name:MPMoviePlayerWillEnterFullscreenNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(movieEventFullscreenHandler:)
name:MPMoviePlayerDidEnterFullscreenNotification
object:nil];
}
- (void)movieEventFullscreenHandler:(NSNotification*)notification {
[player setFullscreen:NO animated:NO];
[player setControlStyle:MPMovieControlStyleEmbedded];
}
How can I dismiss that video screen by touching the Done button? Thanks guys.
You can use the notification of MPMoviePlayerPlaybackDidFinishNotification to observe the done button.
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(playObserver:)name:MPMoviePlayerPlaybackDidFinishNotification object:nil];
and then,make a judge of quitting.
- (void) playObserver:(NSNotification *)notification
{
MPMoviePlayerController* player = moviePlayerView.moviePlayer;
if (player == [notification object]) {
if (_invalidVideoCount > MOVIE_TRY_TIMES) {
[self dismissViewController];
}
_invalidVideoCount++;
int reason = [[[notification userInfo] objectForKey:MPMoviePlayerPlaybackDidFinishReasonUserInfoKey] intValue];
//Whether continuous playback
if (![SINGLETON_CALL(SystemInfoManager) boolValueForKey:UserContinuousPlayEnableKey]) {
[self playFinishWithForce:YES];
return;
}
switch (reason) {
case MPMovieFinishReasonUserExited:
[self playFinishWithForce:YES];
break;
case MPMovieFinishReasonPlaybackError:
[self playFinishWithForce:YES];
break;
case MPMovieFinishReasonPlaybackEnded:
movieTryTimes = 0;
[self playFinishWithForce:NO];
break;
default:
break;
}
}
}
and the last.
- (void)playFinishWithForce:(BOOL)force
{
FileInfoItem *item = ARRAY_OBJECT_AT_INDEX(_playlist, _currentIndex);
BOOL quit = force || !item;
if (quit) {
[self dismissViewController];
} else {
[self playMovieWithItem:item];
}
}
Also you can use the notification of MPMoviePlayerPlaybackStateDidChangeNotification to make any observe.something detail see MPMoviePlayerController.h or https://developer.apple.com/library/ios/documentation/MediaPlayer/Reference/MPMoviePlayerController_Class/Reference/Reference.html
I have found the problem. That's I laid [player stop] in the viewWillDisAppear so can't handle the notification. I fixed temporary by changing it to [player pause]. I appreciated any kind of your helps.

SLComposeViewController cancel doesn't close the VC from one tap

I have problem with the attached codе. It have to close the currently displayed modalViewController when the user tap once on the cancel button instead of twice as it do now.
Code
- (BOOL)isIOS6 {
BOOL native = YES;
if([[[UIDevice currentDevice] systemVersion] floatValue] < 6.0f){
native = NO;
}
return native;
}
- (void)twitterShare {
DLog(#"is ios6: %d", [self isIOS6]);
if ([self isIOS6]) {
if ([SLComposeViewController isAvailableForServiceType:SLServiceTypeTwitter])
{
NSString *textToShare = #"Test";
SLComposeViewController *twitterComposeViewController = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeTwitter];
twitterComposeViewController.completionHandler = ^(SLComposeViewControllerResult result){
DLog(#"result: %d", result);
if (result == 1) {
Dlog(#"Shared");
[[NSNotificationCenter defaultCenter] postNotificationName:#"notitificationName" object:nil];
DLog(#"Sended provide bonus notification");
[self disableButtonWithTag:GrowthButtonTwitterConnectTag];
DLog(#"disable that button.");
} else {
Dlog(#"canceled...");
}
};
[twitterComposeViewController setInitialText:textToShare];
[self presentViewController:twitterComposeViewController animated:YES completion:nil];
} else {
DLog(#"Twitter not available");
}
} else {
// iOS 5 not supported message
[[[[UIAlertView alloc] initWithTitle:NSLocalizedString(#"ATTENTION", nil)
message:NSLocalizedString(#"IOS6_OR_ABOVE_FEATURE", nil)
delegate:nil
cancelButtonTitle:NSLocalizedString(#"OK", nil)
otherButtonTitles:nil, nil] autorelease] show];
}
}
I've manage to fix that issue with the following code:
tweetSheet.completionHandler = ^(SLComposeViewControllerResult result) {
switch(result) {
// This means the user cancelled without sending the Tweet
case SLComposeViewControllerResultCancelled:
break;
// This means the user hit 'Send'
case SLComposeViewControllerResultDone:
[[NSNotificationCenter defaultCenter] postNotificationName:#"kGrowthProvideTwitterBonus" object:nil];
DLog(#"Sended provide bonus notification");
[self disableButtonWithTag:TTGrowthButtonTwitterConnectTag];
break;
}
// dismiss the Tweet Sheet
dispatch_async(dispatch_get_main_queue(), ^{
[self dismissViewControllerAnimated:NO completion:^{
NSLog(#"Tweet Sheet has been dismissed.");
}];
});
};

AVQueuePlayer is pausing but play icon won't disappear

I'm building an application that uses an AVQueuePlayer to stream audio. I have my AVAudioSession set up with the category AVAudioSessionCategoryPlayback and I'm able to receive events from remoteControlReceivedWithEvent:. However, when I pause my audio session, the icon in the status bar does not disappear, nor does the pause/play button in the App Switcher change to play. The audio pauses, but the icons never change. Do you know why this might be happening?
I also use an MPMusicPlayerController to play music from the iPod music player. Both players are always initialized, however only one plays at a time. When the app opens, if I play something from the MPMusicPlayerController first, the AVQueuePlayer doesn't have this pause conflict anymore. It only has this problem when you play from the AVQueuePlayer first. I included the code to show you what I'm doing.
FYI- My MPMusicController is self.musicPlayer. My AVQueuePlayer is self.radioPlayer. After pausing, the status of my AVQueuePlayer is AVPlayerStatusReadyToPlay.
- (void)viewDidLoad {
[super viewDidLoad];
self.musicPlayer = [MPMusicPlayerController iPodMusicPlayer];
self.musicPlayer.nowPlayingItem = self.currentSong;
self.musicPlayer.shuffleMode = MPMusicShuffleModeSongs;
self.musicPlayer.repeatMode = MPMusicRepeatModeAll;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:nil error:nil];
[[AVAudioSession sharedInstance] setActive:YES error:nil];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(radioItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[_radioPlayer currentItem]];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void)viewWillDisappear:(BOOL)animated
{
[self resignFirstResponder];
if (self.source == LIBRARY)
{
[self.parentDelgate reloadInformation];
}
}
- (void)viewDidAppear:(BOOL)animated
{
if (self.source == RADIO)
{
// Code that sets the URLs for the AVQueuePlayer
[self initializeMusicPlayer];
[self prepareRadioPlayer];
}
else if ( self.source == LIBRARY ) {
if ( self.currentSong != self.musicPlayer.nowPlayingItem || self.playlist != nil)
{
[self initializeMusicPlayer];
self.musicPlayer.nowPlayingItem = self.currentSong;
}
}
}
- (void)initializeMusicPlayer {
if ( self.source == LIBRARY )
{
[self.musicPlayer setQueueWithItemCollection:[MPMediaItemCollection collectionWithItems:(NSArray *)self.tracks]];
if ([self.radioPlayer rate] != 0.0)
[self.radioPlayer pause];
[self.musicPlayer play];
self.status = PLAYING;
}
else if ( self.source == RADIO )
{
if ( self.musicPlayer.playbackState == MPMusicPlaybackStatePlaying )
[self.musicPlayer pause];
}
}
- (IBAction)pausePressed:(UIButton *)sender {
if ( self.source == LIBRARY )
{
[self.musicPlayer pause];
}
else if (self.source == RADIO)
{
[self.radioPlayer pause];
}
[self onStatePaused];
}
- (void)onStatePaused {
// UI Stuff
}
- (void)endSession {
[self.musicPlayer stop];
[self.radioPlayer pause];
[self.radioPlayer removeAllItems];
// Present different view
}
Any ideas?
I figured out the problem. I was adding multiple instances of observers to the AVQueuePlayer/AVPlayerItems which was interfering with this.

Take a picture in iOS without UIImagePicker and without preview it

Do you know any way / method to take a photo in iOS and saving it to camera Roll only with a simple button pressure without showing any preview?
I already know how to show the camera view but it show the preview of the image and the user need to click the take photo button to take the photo.
In few Words: the user click the button, the picture is taken, without previews nor double checks to take / save the photo.
I already found the takePicture method of UIIMagePickerController Class http://developer.apple.com/library/ios/documentation/uikit/reference/UIImagePickerController_Class/UIImagePickerController/UIImagePickerController.html#//apple_ref/occ/instm/UIImagePickerController/takePicture
Set the showsCameraControls-Property to NO.
poc = [[UIImagePickerController alloc] init];
[poc setTitle:#"Take a photo."];
[poc setDelegate:self];
[poc setSourceType:UIImagePickerControllerSourceTypeCamera];
poc.showsCameraControls = NO;
You also have to add your own Controls as a custom view on the top of poc.view. But that is very simple and you can add your own UI-style by that way.
You receive the image-data as usually within the imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:
To take the photo, you call
[poc takePicture];
from your custom button.
Hope, that works for you.
Assuming you want a point-and-shoot method, you can create an AVSession and just call the UIImageWriteToSavedPhotosAlbum method.
Here is a link that goes into that exact process: http://www.musicalgeometry.com/?p=1297
It's also worth noting that your users need to have given the app access to their camera roll or you may experience issues saving the images.
You need to design your own custom preview according to your size, on capture button pressed and call buttonPressed method and do stuff what you want
(void)buttonPressed:(UIButton *)sender {
NSLog(#" Capture Clicked");
[self.imagePicker takePicture];
//[NSTimer scheduledTimerWithTimeInterval:3.0f target:self
selector:#selector(timerFired:) userInfo:nil repeats:NO];
}
following is code that will take photo without showing preview screen. when i tried the accepted answer, which uses UIImagePickerController, the preview screen showed, then auto disappeared. with the code below, user taps 'takePhoto' button, and the devices takes photo with zero change to UI (in my app, i add a green check mark next to take photo button). the code below is from apple https://developer.apple.com/LIBRARY/IOS/samplecode/AVCam/Introduction/Intro.html with the 'extra functions' (that do not relate to taking still photo) commented out. thank you incmiko for suggesting this code in your answer iOS take photo from camera without modalViewController.
updating code, 26 mar 2015:
to trigger snap photo:
[self snapStillImage:sender];
in .h file:
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
// include code below in header file, after #import and before #interface
// avfoundation copy paste code
static void * CapturingStillImageContext = &CapturingStillImageContext;
static void * RecordingContext = &RecordingContext;
static void * SessionRunningAndDeviceAuthorizedContext = &SessionRunningAndDeviceAuthorizedContext;
// avfoundation, include code below after #interface
// avf - Session management.
#property (nonatomic) dispatch_queue_t sessionQueue; // Communicate with the session and other session objects on this queue.
#property (nonatomic) AVCaptureSession *session;
#property (nonatomic) AVCaptureDeviceInput *videoDeviceInput;
#property (nonatomic) AVCaptureMovieFileOutput *movieFileOutput;
#property (nonatomic) AVCaptureStillImageOutput *stillImageOutput;
// avf - Utilities.
#property (nonatomic) UIBackgroundTaskIdentifier backgroundRecordingID;
#property (nonatomic, getter = isDeviceAuthorized) BOOL deviceAuthorized;
#property (nonatomic, readonly, getter = isSessionRunningAndDeviceAuthorized) BOOL sessionRunningAndDeviceAuthorized;
#property (nonatomic) BOOL lockInterfaceRotation;
#property (nonatomic) id runtimeErrorHandlingObserver;
in .m file:
#pragma mark - AV Foundation
- (BOOL)isSessionRunningAndDeviceAuthorized
{
return [[self session] isRunning] && [self isDeviceAuthorized];
}
+ (NSSet *)keyPathsForValuesAffectingSessionRunningAndDeviceAuthorized
{
return [NSSet setWithObjects:#"session.running", #"deviceAuthorized", nil];
}
// call following method from viewDidLoad
- (void)CreateAVCaptureSession
{
// Create the AVCaptureSession
AVCaptureSession *session = [[AVCaptureSession alloc] init];
[self setSession:session];
// Check for device authorization
[self checkDeviceAuthorizationStatus];
// In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
// Why not do all of this on the main queue?
// -[AVCaptureSession startRunning] is a blocking call which can take a long time. We dispatch session setup to the sessionQueue so that the main queue isn't blocked (which keeps the UI responsive).
dispatch_queue_t sessionQueue = dispatch_queue_create("session queue", DISPATCH_QUEUE_SERIAL);
[self setSessionQueue:sessionQueue];
dispatch_async(sessionQueue, ^{
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
NSError *error = nil;
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:AVCaptureDevicePositionFront];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:&error];
if (error)
{
NSLog(#"%#", error);
}
if ([session canAddInput:videoDeviceInput])
{
[session addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
dispatch_async(dispatch_get_main_queue(), ^{
// Why are we dispatching this to the main queue?
// Because AVCaptureVideoPreviewLayer is the backing layer for AVCamPreviewView and UIView can only be manipulated on main thread.
// Note: As an exception to the above rule, it is not necessary to serialize video orientation changes on the AVCaptureVideoPreviewLayer’s connection with other session manipulation.
});
}
/* AVCaptureDevice *audioDevice = [[AVCaptureDevice devicesWithMediaType:AVMediaTypeAudio] firstObject];
AVCaptureDeviceInput *audioDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
if (error)
{
NSLog(#"%#", error);
}
if ([session canAddInput:audioDeviceInput])
{
[session addInput:audioDeviceInput];
}
*/
AVCaptureMovieFileOutput *movieFileOutput = [[AVCaptureMovieFileOutput alloc] init];
if ([session canAddOutput:movieFileOutput])
{
[session addOutput:movieFileOutput];
AVCaptureConnection *connection = [movieFileOutput connectionWithMediaType:AVMediaTypeVideo];
if ([connection isVideoStabilizationSupported])
[connection setEnablesVideoStabilizationWhenAvailable:YES];
[self setMovieFileOutput:movieFileOutput];
}
AVCaptureStillImageOutput *stillImageOutput = [[AVCaptureStillImageOutput alloc] init];
if ([session canAddOutput:stillImageOutput])
{
[stillImageOutput setOutputSettings:#{AVVideoCodecKey : AVVideoCodecJPEG}];
[session addOutput:stillImageOutput];
[self setStillImageOutput:stillImageOutput];
}
});
}
// call method below from viewWilAppear
- (void)AVFoundationStartSession
{
dispatch_async([self sessionQueue], ^{
[self addObserver:self forKeyPath:#"sessionRunningAndDeviceAuthorized" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:SessionRunningAndDeviceAuthorizedContext];
[self addObserver:self forKeyPath:#"stillImageOutput.capturingStillImage" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:CapturingStillImageContext];
[self addObserver:self forKeyPath:#"movieFileOutput.recording" options:(NSKeyValueObservingOptionOld | NSKeyValueObservingOptionNew) context:RecordingContext];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
__weak ViewController *weakSelf = self;
[self setRuntimeErrorHandlingObserver:[[NSNotificationCenter defaultCenter] addObserverForName:AVCaptureSessionRuntimeErrorNotification object:[self session] queue:nil usingBlock:^(NSNotification *note) {
ViewController *strongSelf = weakSelf;
dispatch_async([strongSelf sessionQueue], ^{
// Manually restarting the session since it must have been stopped due to an error.
[[strongSelf session] startRunning];
});
}]];
[[self session] startRunning];
});
}
// call method below from viewDidDisappear
- (void)AVFoundationStopSession
{
dispatch_async([self sessionQueue], ^{
[[self session] stopRunning];
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:[[self videoDeviceInput] device]];
[[NSNotificationCenter defaultCenter] removeObserver:[self runtimeErrorHandlingObserver]];
[self removeObserver:self forKeyPath:#"sessionRunningAndDeviceAuthorized" context:SessionRunningAndDeviceAuthorizedContext];
[self removeObserver:self forKeyPath:#"stillImageOutput.capturingStillImage" context:CapturingStillImageContext];
[self removeObserver:self forKeyPath:#"movieFileOutput.recording" context:RecordingContext];
});
}
- (BOOL)prefersStatusBarHidden
{
return YES;
}
- (BOOL)shouldAutorotate
{
// Disable autorotation of the interface when recording is in progress.
return ![self lockInterfaceRotation];
}
- (NSUInteger)supportedInterfaceOrientations
{
return UIInterfaceOrientationMaskAll;
}
- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration
{
// [[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] setVideoOrientation:(AVCaptureVideoOrientation)toInterfaceOrientation];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == CapturingStillImageContext)
{
BOOL isCapturingStillImage = [change[NSKeyValueChangeNewKey] boolValue];
if (isCapturingStillImage)
{
[self runStillImageCaptureAnimation];
}
}
else if (context == RecordingContext)
{
BOOL isRecording = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRecording)
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setTitle:NSLocalizedString(#"Stop", #"Recording button stop title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setTitle:NSLocalizedString(#"Record", #"Recording button record title") forState:UIControlStateNormal];
// [[self recordButton] setEnabled:YES];
}
});
}
else if (context == SessionRunningAndDeviceAuthorizedContext)
{
BOOL isRunning = [change[NSKeyValueChangeNewKey] boolValue];
dispatch_async(dispatch_get_main_queue(), ^{
if (isRunning)
{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
}
else
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
}
});
}
else
{
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
#pragma mark Actions
- (IBAction)toggleMovieRecording:(id)sender
{
// [[self recordButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
if (![[self movieFileOutput] isRecording])
{
[self setLockInterfaceRotation:YES];
if ([[UIDevice currentDevice] isMultitaskingSupported])
{
// Setup background task. This is needed because the captureOutput:didFinishRecordingToOutputFileAtURL: callback is not received until AVCam returns to the foreground unless you request background execution time. This also ensures that there will be time to write the file to the assets library when AVCam is backgrounded. To conclude this background execution, -endBackgroundTask is called in -recorder:recordingDidFinishToOutputFileURL:error: after the recorded file has been saved.
[self setBackgroundRecordingID:[[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:nil]];
}
// Update the orientation on the movie file output video connection before starting recording.
// [[[self movieFileOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Turning OFF flash for video recording
[ViewController setFlashMode:AVCaptureFlashModeOff forDevice:[[self videoDeviceInput] device]];
// Start recording to a temporary file.
NSString *outputFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[#"movie" stringByAppendingPathExtension:#"mov"]];
[[self movieFileOutput] startRecordingToOutputFileURL:[NSURL fileURLWithPath:outputFilePath] recordingDelegate:self];
}
else
{
[[self movieFileOutput] stopRecording];
}
});
}
- (IBAction)changeCamera:(id)sender
{
// [[self cameraButton] setEnabled:NO];
// [[self recordButton] setEnabled:NO];
// [[self stillButton] setEnabled:NO];
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *currentVideoDevice = [[self videoDeviceInput] device];
AVCaptureDevicePosition preferredPosition = AVCaptureDevicePositionUnspecified;
AVCaptureDevicePosition currentPosition = [currentVideoDevice position];
switch (currentPosition)
{
case AVCaptureDevicePositionUnspecified:
preferredPosition = AVCaptureDevicePositionBack;
break;
case AVCaptureDevicePositionBack:
preferredPosition = AVCaptureDevicePositionFront;
break;
case AVCaptureDevicePositionFront:
preferredPosition = AVCaptureDevicePositionBack;
break;
}
AVCaptureDevice *videoDevice = [ViewController deviceWithMediaType:AVMediaTypeVideo preferringPosition:preferredPosition];
AVCaptureDeviceInput *videoDeviceInput = [AVCaptureDeviceInput deviceInputWithDevice:videoDevice error:nil];
[[self session] beginConfiguration];
[[self session] removeInput:[self videoDeviceInput]];
if ([[self session] canAddInput:videoDeviceInput])
{
[[NSNotificationCenter defaultCenter] removeObserver:self name:AVCaptureDeviceSubjectAreaDidChangeNotification object:currentVideoDevice];
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:videoDevice];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(subjectAreaDidChange:) name:AVCaptureDeviceSubjectAreaDidChangeNotification object:videoDevice];
[[self session] addInput:videoDeviceInput];
[self setVideoDeviceInput:videoDeviceInput];
}
else
{
[[self session] addInput:[self videoDeviceInput]];
}
[[self session] commitConfiguration];
dispatch_async(dispatch_get_main_queue(), ^{
// [[self cameraButton] setEnabled:YES];
// [[self recordButton] setEnabled:YES];
// [[self stillButton] setEnabled:YES];
});
});
}
- (IBAction)snapStillImage:(id)sender
{
dispatch_async([self sessionQueue], ^{
// Update the orientation on the still image output video connection before capturing.
// [[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] setVideoOrientation:[[(AVCaptureVideoPreviewLayer *)[[self previewView] layer] connection] videoOrientation]];
// Flash set to Auto for Still Capture
[ViewController setFlashMode:AVCaptureFlashModeAuto forDevice:[[self videoDeviceInput] device]];
// Capture a still image.
[[self stillImageOutput] captureStillImageAsynchronouslyFromConnection:[[self stillImageOutput] connectionWithMediaType:AVMediaTypeVideo] completionHandler:^(CMSampleBufferRef imageDataSampleBuffer, NSError *error) {
if (imageDataSampleBuffer)
{
NSData *imageData = [AVCaptureStillImageOutput jpegStillImageNSDataRepresentation:imageDataSampleBuffer];
UIImage *image = [[UIImage alloc] initWithData:imageData];
// do someting good with saved image
[self saveImageToParse:image];
}
}];
});
}
- (IBAction)focusAndExposeTap:(UIGestureRecognizer *)gestureRecognizer
{
// CGPoint devicePoint = [(AVCaptureVideoPreviewLayer *)[[self previewView] layer] captureDevicePointOfInterestForPoint:[gestureRecognizer locationInView:[gestureRecognizer view]]];
// [self focusWithMode:AVCaptureFocusModeAutoFocus exposeWithMode:AVCaptureExposureModeAutoExpose atDevicePoint:devicePoint monitorSubjectAreaChange:YES];
}
- (void)subjectAreaDidChange:(NSNotification *)notification
{
CGPoint devicePoint = CGPointMake(.5, .5);
[self focusWithMode:AVCaptureFocusModeContinuousAutoFocus exposeWithMode:AVCaptureExposureModeContinuousAutoExposure atDevicePoint:devicePoint monitorSubjectAreaChange:NO];
}
#pragma mark File Output Delegate
- (void)captureOutput:(AVCaptureFileOutput *)captureOutput didFinishRecordingToOutputFileAtURL:(NSURL *)outputFileURL fromConnections:(NSArray *)connections error:(NSError *)error
{
if (error)
NSLog(#"%#", error);
[self setLockInterfaceRotation:NO];
// Note the backgroundRecordingID for use in the ALAssetsLibrary completion handler to end the background task associated with this recording. This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's -isRecording is back to NO — which happens sometime after this method returns.
UIBackgroundTaskIdentifier backgroundRecordingID = [self backgroundRecordingID];
[self setBackgroundRecordingID:UIBackgroundTaskInvalid];
[[[ALAssetsLibrary alloc] init] writeVideoAtPathToSavedPhotosAlbum:outputFileURL completionBlock:^(NSURL *assetURL, NSError *error) {
if (error)
NSLog(#"%#", error);
[[NSFileManager defaultManager] removeItemAtURL:outputFileURL error:nil];
if (backgroundRecordingID != UIBackgroundTaskInvalid)
[[UIApplication sharedApplication] endBackgroundTask:backgroundRecordingID];
}];
}
#pragma mark Device Configuration
- (void)focusWithMode:(AVCaptureFocusMode)focusMode exposeWithMode:(AVCaptureExposureMode)exposureMode atDevicePoint:(CGPoint)point monitorSubjectAreaChange:(BOOL)monitorSubjectAreaChange
{
dispatch_async([self sessionQueue], ^{
AVCaptureDevice *device = [[self videoDeviceInput] device];
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
if ([device isFocusPointOfInterestSupported] && [device isFocusModeSupported:focusMode])
{
[device setFocusMode:focusMode];
[device setFocusPointOfInterest:point];
}
if ([device isExposurePointOfInterestSupported] && [device isExposureModeSupported:exposureMode])
{
[device setExposureMode:exposureMode];
[device setExposurePointOfInterest:point];
}
[device setSubjectAreaChangeMonitoringEnabled:monitorSubjectAreaChange];
[device unlockForConfiguration];
}
else
{
NSLog(#"%#", error);
}
});
}
+ (void)setFlashMode:(AVCaptureFlashMode)flashMode forDevice:(AVCaptureDevice *)device
{
if ([device hasFlash] && [device isFlashModeSupported:flashMode])
{
NSError *error = nil;
if ([device lockForConfiguration:&error])
{
[device setFlashMode:flashMode];
[device unlockForConfiguration];
}
else
{
NSLog(#"%#", error);
}
}
}
+ (AVCaptureDevice *)deviceWithMediaType:(NSString *)mediaType preferringPosition:(AVCaptureDevicePosition)position
{
NSArray *devices = [AVCaptureDevice devicesWithMediaType:mediaType];
AVCaptureDevice *captureDevice = [devices firstObject];
for (AVCaptureDevice *device in devices)
{
if ([device position] == position)
{
captureDevice = device;
break;
}
}
return captureDevice;
}
#pragma mark UI
- (void)runStillImageCaptureAnimation
{
/*
dispatch_async(dispatch_get_main_queue(), ^{
[[[self previewView] layer] setOpacity:0.0];
[UIView animateWithDuration:.25 animations:^{
[[[self previewView] layer] setOpacity:1.0];
}];
});
*/
}
- (void)checkDeviceAuthorizationStatus
{
NSString *mediaType = AVMediaTypeVideo;
[AVCaptureDevice requestAccessForMediaType:mediaType completionHandler:^(BOOL granted) {
if (granted)
{
//Granted access to mediaType
[self setDeviceAuthorized:YES];
}
else
{
//Not granted access to mediaType
dispatch_async(dispatch_get_main_queue(), ^{
[[[UIAlertView alloc] initWithTitle:#"AVCam!"
message:#"AVCam doesn't have permission to use Camera, please change privacy settings"
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil] show];
[self setDeviceAuthorized:NO];
});
}
}];
}

AVPlayer not playing MP3 audio file in documents directory iOS

I'm using AVPlayer to play a MP3 located in the documents directory (file is confirmed to be in there) - I load the AVPlayerItem wait for the AVPlayerItemStatusReadyToPlay then instantiate the AVPlayer with the item and play.
The AVPlayerItemStatusReadyToPlay does get called, but no audio actually plays, anyone have an idea why?
- (void)checkFileExists {
if (![[NSFileManager defaultManager] fileExistsAtPath:[self.urlForEightBarAudioFile path]]) {
[self beginEightBarDownload];
} else {
// set up audio
[self setupAudio];
//NSLog(#"file %# already exists", [self.urlForEightBarAudioFile path]);
}
}
- (void)setupAudio
{
AVAsset *eightBarAsset = [AVAsset assetWithURL:self.urlForEightBarAudioFile];
self.eightBarsPlayerItem = [[AVPlayerItem alloc] initWithAsset:eightBarAsset];
[self.eightBarsPlayerItem addObserver:self forKeyPath:#"status" options:0 context:nil];
}
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if ([object isKindOfClass:[AVPlayerItem class]])
{
AVPlayerItem *item = (AVPlayerItem *)object;
if ([keyPath isEqualToString:#"status"])
{
switch(item.status)
{
case AVPlayerItemStatusFailed:
break;
case AVPlayerItemStatusReadyToPlay:
self.player = [[AVPlayer alloc] initWithPlayerItem:self.eightBarsPlayerItem];
[self.player play];
NSLog(#"player item status is ready to play");
break;
case AVPlayerItemStatusUnknown:
NSLog(#"player item status is unknown");
break;
}
}
else if ([keyPath isEqualToString:#"playbackBufferEmpty"])
{
if (item.playbackBufferEmpty)
{
NSLog(#"player item playback buffer is empty");
}
}
}
}
Do this:
- (void)setupAudio
{
if([NSFileManager defaultManager] fileExistsAtPath:[self.urlForEightBarAudioFile absoluteString]])
{
AVAsset *eightBarAsset = [AVAsset assetWithURL:self.urlForEightBarAudioFile];
self.eightBarsPlayerItem = [[AVPlayerItem alloc] initWithAsset:eightBarAsset];
self.eightBarsPlayer = [AVPlayer playerWithPlayerItem:self.eightBarsPlayerItem]; //forgot this line
[self.eightBarsPlayer addObserver:self forKeyPath:#"status" options:0 context:nil]; // add observer for player not item
}
}
Refer avplayer-and-local-files link
in swift
func setupAudio() {
if NSFileManager.defaultManager().fileExistsAtPath(self.urlForEightBarAudioFile.absoluteString) {
self.eightBarsPlayerItem = AVPlayerItem(asset: AVAsset(URL: self.urlForEightBarAudioFile))
self.eightBarsPlayer = AVPlayer(playerItem: self.eightBarsPlayerItem)
}
}
- (void)setupAudio
{
dispatch_async(dispatch_get_main_queue(), ^{
AVAsset *eightBarAsset = [AVAsset assetWithURL:self.urlForEightBarAudioFile];
self.eightBarsPlayerItem = [[AVPlayerItem alloc] initWithAsset:eightBarAsset];
self.eightBarsPlayer = [AVPlayer playerWithPlayerItem:self.eightBarsPlayerItem]; //forgot this line
[self.eightBarsPlayer addObserver:self forKeyPath:#"status" options:0 context:nil]; // add observer for player not item
});
}