I’m trying to play a remote MP3 file in my Xcode project, however the implementation below, using MPMoviePlayerController is not working for me and is throwing an exception.
AVPlayerItem was deallocated while key value observers were still
registered with it.
My .h file
#import <MediaPlayer/MediaPlayer.h>
@property (nonatomic, strong) MPMoviePlayerController *moviePlayer;
My .m file
@synthesize moviePlayer = _moviePlayer;
- (void)playEnglish
{
NSURL *url = [NSURL URLWithString:_audioUrlEnglish];
_moviePlayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:_moviePlayer];
_moviePlayer.controlStyle = MPMovieControlStyleDefault;
_moviePlayer.shouldAutoplay = YES;
[self.view addSubview:_moviePlayer.view];
[_moviePlayer setFullscreen:YES animated:YES];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
MPMoviePlayerController *player = [notification object];
[[NSNotificationCenter defaultCenter]
removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:player];
if ([player
respondsToSelector:@selector(setFullscreen:animated:)])
{
[player.view removeFromSuperview];
}
}
You’ve specified a synthesized property for your player, but you’re then assigning directly to the ivar.
Instead of:
You should:
This will ensure that your object is properly retained (if you are using automatic reference counting). Without this, it appears your player is not being retained and that would explain your error.
Additionally, you are assigning/accessing instance variables at several other places in your code. Best practice in Cocoa generally avoids directly touching ivars at all (there are some exceptions, however there are even fewer when using ARC, and I don’t see any examples here that would merit direct assignment).