Can avplayer play music from mpmusicplayercontroller - iphone

is this possible AVPlayer fetch music from ipodlibrary from MPMusicPlayerController and play ,since avplayer cannot access iPodMusicPlayer from MPMusicPlayerController , since AVPlayer support background playing and access to remoteEvents.
The code shown below is from addMusic project. so any help would be appreciated .Thank you
void audioRouteChangeListenerCallback (
void *inUserData,
AudioSessionPropertyID inPropertyID,
UInt32 inPropertyValueSize,
const void *inPropertyValue
) {
// ensure that this callback was invoked for a route change
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
// This callback, being outside the implementation block, needs a reference to the
// MainViewController object, which it receives in the inUserData parameter.
// You provide this reference when registering this callback (see the call to
// AudioSessionAddPropertyListener).
MainViewController *controller = (MainViewController *) inUserData;
// if application sound is not playing, there's nothing to do, so return.
if (controller.appSoundPlayer.playing == 0 ) {
NSLog (#"Audio route change while application audio is stopped.");
return;
} else {
// Determines the reason for the route change, to ensure that it is not
// because of a category change.
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef =
CFDictionaryGetValue (
routeChangeDictionary,
CFSTR (kAudioSession_AudioRouteChangeKey_Reason)
);
SInt32 routeChangeReason;
CFNumberGetValue (
routeChangeReasonRef,
kCFNumberSInt32Type,
&routeChangeReason
);
// "Old device unavailable" indicates that a headset was unplugged, or that the
// device was removed from a dock connector that supports audio output. This is
// the recommended test for when to pause audio.
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[controller.appSoundPlayer pause];
NSLog (#"Output device removed, so application audio was paused.");
UIAlertView *routeChangeAlertView =
[[UIAlertView alloc] initWithTitle: NSLocalizedString (#"Playback Paused", #"Title for audio hardware route-changed alert view")
message: NSLocalizedString (#"Audio output was changed", #"Explanation for route-changed alert view")
delegate: controller
cancelButtonTitle: NSLocalizedString (#"StopPlaybackAfterRouteChange", #"Stop button title")
otherButtonTitles: NSLocalizedString (#"ResumePlaybackAfterRouteChange", #"Play button title"), nil];
[routeChangeAlertView show];
// release takes place in alertView:clickedButtonAtIndex: method
} else {
NSLog (#"A route change occurred that does not require pausing of application audio.");
}
}
}
#implementation MainViewController
#synthesize artworkItem;
#synthesize userMediaItemCollection;
#synthesize playBarButton;
#synthesize pauseBarButton;
#synthesize musicPlayer;
#synthesize navigationBar;
#synthesize noArtworkImage; item has no associated artwork
#synthesize backgroundColorTimer;
#synthesize nowPlayingLabel;
#synthesize appSoundButton;
#synthesize addOrShowMusicButton;
#synthesize appSoundPlayer;
#synthesize soundFileURL;
#synthesize interruptedOnPlayback;
#synthesize playedMusicOnce;
#synthesize playing;
#implementation MainViewController
#synthesize artworkItem; // the now-playing media item's artwork image, displayed in the Navigation bar
#synthesize userMediaItemCollection; // the media item collection created by the user, using the media item picker
#synthesize playBarButton; // the button for invoking Play on the music player
#synthesize pauseBarButton; // the button for invoking Pause on the music player
#synthesize musicPlayer; // the music player, which plays media items from the iPod library
#synthesize navigationBar; // the application's Navigation bar
#synthesize noArtworkImage; // an image to display when a media item has no associated artwork
#synthesize backgroundColorTimer; // a timer for changing the background color -- represents an application that is
// doing something else while iPod music is playing
#synthesize nowPlayingLabel; // descriptive text shown on the main screen about the now-playing media item
#synthesize appSoundButton; // the button to invoke playback for the application sound
#synthesize addOrShowMusicButton; // the button for invoking the media item picker. if the user has already
// specified a media item collection, the title changes to "Show Music" and
// the button invokes a table view that shows the specified collection
#synthesize appSoundPlayer; // An AVAudioPlayer object for playing application sound
#synthesize soundFileURL; // The path to the application sound
#synthesize interruptedOnPlayback; // A flag indicating whether or not the application was interrupted during
// application audio playback
#synthesize playedMusicOnce; // A flag indicating if the user has played iPod library music at least one time
// since application launch.
#synthesize playing; // An application that responds to interruptions must keep track of its playing/
// not-playing state.
#pragma mark Music control
- (IBAction) AddMusicOrShowMusic: (id) sender {
// if the user has already chosen some music, display that list
if (userMediaItemCollection) {
MusicTableViewController *controller = [[MusicTableViewController alloc] initWithNibName: #"MusicTableView" bundle: nil];
controller.delegate = self;
controller.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController: controller animated: YES];
[controller release];
} else {
MPMediaPickerController *picker =
[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = YES;
picker.prompt = NSLocalizedString (#"Add songs to play", "Prompt in media item picker");
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleDefault animated: YES];
[self presentModalViewController: picker animated: YES];
[picker release];
}
}
- (void) updatePlayerQueueWithMediaCollection: (MPMediaItemCollection *) mediaItemCollection {
// Configure the music player, but only if the user chose at least one song to play
if (mediaItemCollection) {
if (userMediaItemCollection == nil) {
[self setUserMediaItemCollection: mediaItemCollection];
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];
[self setPlayedMusicOnce: YES];
[musicPlayer play];
} else {
BOOL wasPlaying = NO;
if (musicPlayer.playbackState == MPMusicPlaybackStatePlaying) {
wasPlaying = YES;
}
MPMediaItem *nowPlayingItem = musicPlayer.nowPlayingItem;
NSTimeInterval currentPlaybackTime = musicPlayer.currentPlaybackTime;
NSMutableArray *combinedMediaItems = [[userMediaItemCollection items] mutableCopy];
NSArray *newMediaItems = [mediaItemCollection items];
[combinedMediaItems addObjectsFromArray: newMediaItems];
[self setUserMediaItemCollection: [MPMediaItemCollection collectionWithItems: (NSArray *) combinedMediaItems]];
[combinedMediaItems release];
[musicPlayer setQueueWithItemCollection: userMediaItemCollection];
musicPlayer.nowPlayingItem = nowPlayingItem;
musicPlayer.currentPlaybackTime = currentPlaybackTime;
if (wasPlaying) {
[musicPlayer play];
}
}
navigationBar.topItem.leftBarButtonItem.enabled = YES;
[addOrShowMusicButton setTitle: NSLocalizedString (#"Show Music", #"Alternate title for 'Add Music' button, after user has chosen some music")
forState: UIControlStateNormal];
}
}
- (void) restorePlaybackState {
if (musicPlayer.playbackState == MPMusicPlaybackStateStopped && userMediaItemCollection) {
[addOrShowMusicButton setTitle: NSLocalizedString (#"Show Music", #"Alternate title for 'Add Music' button, after user has chosen some music")
forState: UIControlStateNormal];
if (playedMusicOnce == NO) {
[self setPlayedMusicOnce: YES];
[musicPlayer play];
}
}
}
#pragma mark Media item picker delegate methods________
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection {
[self dismissModalViewControllerAnimated: YES];
[self updatePlayerQueueWithMediaCollection: mediaItemCollection];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated: YES];
}
- (void) mediaPickerDidCancel: (MPMediaPickerController *) mediaPicker {
[self dismissModalViewControllerAnimated: YES];
[[UIApplication sharedApplication] setStatusBarStyle: UIStatusBarStyleBlackOpaque animated: YES];
}
#pragma mark Music notification handlers__________________
- (void) handle_NowPlayingItemChanged: (id) notification {
MPMediaItem *currentItem = [musicPlayer nowPlayingItem];
UIImage *artworkImage = noArtworkImage;
MPMediaItemArtwork *artwork = [currentItem valueForProperty: MPMediaItemPropertyArtwork];
// Obtain a UIImage object from the MPMediaItemArtwork object
if (artwork) {
artworkImage = [artwork imageWithSize: CGSizeMake (30, 30)];
}
// Obtain a UIButton object and set its background to the UIImage object
UIButton *artworkView = [[UIButton alloc] initWithFrame: CGRectMake (0, 0, 30, 30)];
[artworkView setBackgroundImage: artworkImage forState: UIControlStateNormal];
// Obtain a UIBarButtonItem object and initialize it with the UIButton object
UIBarButtonItem *newArtworkItem = [[UIBarButtonItem alloc] initWithCustomView: artworkView];
[self setArtworkItem: newArtworkItem];
[newArtworkItem release];
[artworkItem setEnabled: NO];
[navigationBar.topItem setRightBarButtonItem: artworkItem animated: YES];
[nowPlayingLabel setText: [
NSString stringWithFormat: #"%# %# %# %#",
NSLocalizedString (#"Now Playing:", #"Label for introducing the now-playing song title and artist"),
[currentItem valueForProperty: MPMediaItemPropertyTitle],
NSLocalizedString (#"by", #"Article between song name and artist name"),
[currentItem valueForProperty: MPMediaItemPropertyArtist]]];
if (musicPlayer.playbackState == MPMusicPlaybackStateStopped) {
[nowPlayingLabel setText: [
NSString stringWithFormat: #"%#",
NSLocalizedString (#"Music-ended Instructions", #"Label for prompting user to play music again after it has stopped")]];
}
}
- (void) handle_PlaybackStateChanged: (id) notification {
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStatePaused) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
} else if (playbackState == MPMusicPlaybackStatePlaying) {
navigationBar.topItem.leftBarButtonItem = pauseBarButton;
} else if (playbackState == MPMusicPlaybackStateStopped) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
// Even though stopped, invoking 'stop' ensures that the music player will play
// its queue from the start.
[musicPlayer stop];
}
}
- (void) handle_iPodLibraryChanged: (id) notification {
]
}
#pragma mark Application playback control_________________
- (IBAction) playAppSound: (id) sender {
[appSoundPlayer play];
playing = YES;
[appSoundButton setEnabled: NO];
}
- (void) alertView: routeChangeAlertView clickedButtonAtIndex: buttonIndex {
if ((NSInteger) buttonIndex == 1) {
[appSoundPlayer play];
} else {
[appSoundPlayer setCurrentTime: 0];
[appSoundButton setEnabled: YES];
}
[routeChangeAlertView release];
}
#pragma mark AV Foundation delegate methods____________
- (void) audioPlayerDidFinishPlaying: (AVAudioPlayer *) appSoundPlayer successfully: (BOOL) flag {
playing = NO;
[appSoundButton setEnabled: YES];
}
- (void) audioPlayerBeginInterruption: player {
NSLog (#"Interrupted. The system has paused audio playback.");
if (playing) {
playing = NO;
interruptedOnPlayback = YES;
}
}
- (void) audioPlayerEndInterruption: player {
NSLog (#"Interruption ended. Resuming audio playback.");
[[AVAudioSession sharedInstance] setActive: YES error: nil];
if (interruptedOnPlayback) {
[appSoundPlayer prepareToPlay];
[appSoundPlayer play];
playing = YES;
interruptedOnPlayback = NO;
}
}
#pragma mark Table view delegate methods
- (void) musicTableViewControllerDidFinish: (MusicTableViewController *) controller {
[self dismissModalViewControllerAnimated: YES];
[self restorePlaybackState];
}
#pragma mark Application setup
- (void) setupApplicationAudio {
NSString *soundFilePath = [[NSBundle mainBundle] pathForResource: #"sound"
ofType: #"caf"];
NSURL *newURL = [[NSURL alloc] initFileURLWithPath: soundFilePath];
self.soundFileURL = newURL;
[newURL release];
[[AVAudioSession sharedInstance] setDelegate: self];
// [[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryAmbient error: nil];
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: nil];
UInt32 doSetProperty = 0;
AudioSessionSetProperty (
kAudioSessionProperty_OverrideCategoryMixWithOthers,
sizeof (doSetProperty),
&doSetProperty
);
// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
kAudioSessionProperty_AudioRouteChange,
audioRouteChangeListenerCallback,
self
);
// Activates the audio session.
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
// Instantiates the AVAudioPlayer object, initializing it with the sound
AVAudioPlayer *newPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL: soundFileURL error: nil];
self.appSoundPlayer = newPlayer;
[newPlayer release];
[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
}
- (void) registerForMediaPlayerNotifications {
NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
[notificationCenter addObserver: self
selector: #selector (handle_NowPlayingItemChanged:)
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[notificationCenter addObserver: self
selector: #selector (handle_PlaybackStateChanged:)
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer beginGeneratingPlaybackNotifications];
}
- (BOOL) useiPodPlayer {
if ([[NSUserDefaults standardUserDefaults] boolForKey: PLAYER_TYPE_PREF_KEY]) {
return YES;
} else {
return NO;
}
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self becomeFirstResponder];
}
- (void) viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[[UIApplication sharedApplication] endReceivingRemoteControlEvents];
[self resignFirstResponder];
}
- (BOOL)canBecomeFirstResponder {
return YES;
}
- (void) remoteControlReceivedWithEvent: (UIEvent *) receivedEvent {
if (receivedEvent.type == UIEventTypeRemoteControl) {
switch (receivedEvent.subtype) {
case UIEventSubtypeRemoteControlTogglePlayPause:
[self togglePlayPause];
break;
case UIEventSubtypeRemoteControlPlay:
[self playAudio];
break;
case UIEventSubtypeRemoteControlPause:
[self pauseAudio];
break;
default:
break;
}
}
}
- (IBAction) playOrPauseMusic: (id)sender {
[self togglePlayPause];
}
- (void)playAudio {
[musicPlayer play];
}
- (void)pauseAudio {
[musicPlayer pause];
}
- (void)togglePlayPause {
MPMusicPlaybackState playbackState = [musicPlayer playbackState];
if (playbackState == MPMusicPlaybackStateStopped || playbackState == MPMusicPlaybackStatePaused) {
[musicPlayer play];
} else if (playbackState == MPMusicPlaybackStatePlaying) {
[musicPlayer pause];
}
}
// Configure the application.
- (void) viewDidLoad {
[super viewDidLoad];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
[self setupApplicationAudio];
[self setPlayedMusicOnce: NO];
[self setNoArtworkImage: [UIImage imageNamed: #"no_artwork.png"]];
[self setPlayBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPlay
target: self
action: #selector (playOrPauseMusic:)]];
[self setPauseBarButton: [[UIBarButtonItem alloc] initWithBarButtonSystemItem: UIBarButtonSystemItemPause
target: self
action: #selector (playOrPauseMusic:)]];
[addOrShowMusicButton setTitle: NSLocalizedString (#"Add Music", #"Title for 'Add Music' button, before user has chosen some music")
forState: UIControlStateNormal];
[appSoundButton setTitle: NSLocalizedString (#"Play App Sound", #"Title for 'Play App Sound' button")
forState: UIControlStateNormal];
[nowPlayingLabel setText: NSLocalizedString (#"Instructions", #"Brief instructions to user, shown at launch")];
if ([self useiPodPlayer]) {
[self setMusicPlayer: [MPMusicPlayerController iPodMusicPlayer]];
if ([musicPlayer nowPlayingItem]) {
navigationBar.topItem.leftBarButtonItem.enabled = YES;
[self handle_NowPlayingItemChanged: nil];
if ([musicPlayer playbackState] == MPMusicPlaybackStatePaused) {
navigationBar.topItem.leftBarButtonItem = playBarButton;
}
}
} else {
[self setMusicPlayer: [MPMusicPlayerController applicationMusicPlayer]];
[musicPlayer setShuffleMode: MPMusicShuffleModeOff];
[musicPlayer setRepeatMode: MPMusicRepeatModeNone];
}
[self registerForMediaPlayerNotifications];
[self setBackgroundColorTimer: [NSTimer scheduledTimerWithTimeInterval: 3.5
target: self
selector: #selector (updateBackgroundColor)
userInfo: nil
repeats: YES]];
}
// Invoked by the backgroundColorTimer.
- (void) updateBackgroundColor {
[UIView beginAnimations: nil context: nil];
[UIView setAnimationDuration: 3.0];
CGFloat redLevel = rand() / (float) RAND_MAX;
CGFloat greenLevel = rand() / (float) RAND_MAX;
CGFloat blueLevel = rand() / (float) RAND_MAX;
self.view.backgroundColor = [UIColor colorWithRed: redLevel
green: greenLevel
blue: blueLevel
alpha: 1.0];
[UIView commitAnimations];
}
#pragma mark Application state management_____________
- (void) didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void) viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerNowPlayingItemDidChangeNotification
object: musicPlayer];
[[NSNotificationCenter defaultCenter] removeObserver: self
name: MPMusicPlayerControllerPlaybackStateDidChangeNotification
object: musicPlayer];
[musicPlayer endGeneratingPlaybackNotifications];
[musicPlayer release];
[artworkItem release];
[backgroundColorTimer invalidate];
[backgroundColorTimer release];
[navigationBar release];
[noArtworkImage release];
[nowPlayingLabel release];
[pauseBarButton release];
[playBarButton release];
[soundFileURL release];
[userMediaItemCollection release];
[super dealloc];
}
#end

These four lines should get you started :)
MPMediaItem *nowPlayingItem = musicPlayer.nowPlayingItem;
NSURL * mediaURL = [nowPlayingItem valueForProperty:MPMediaItemPropertyAssetURL];
AVPlayerItem * myAVPlayerItem = [AVPlayerItem playerItemWithURL:mediaURL];
AVPlayer * myAvPlayer = [AVPlayer playerWithPlayerItem:myAVPlayerItem];

Related

How to add multiple colour in a round progressview after some specific interval in xcode?

I am using a custom progress view in Uiprogressview, and its being filled with a fixed color within 20 seconds, but I want such that it will be filled with the different color after 10 seconds, so that after 2 seconds it will look like a two colored circle,
here is my code:
#import "CEViewController.h"
#interface CEViewController ()
{
}
#end
#implementation CEViewController
#synthesize progressView;
#synthesize progressSlider;
#synthesize playPauseButton;
#synthesize player;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.player = [[[CEPlayer alloc] init] autorelease];
self.player.delegate = self;
UIColor *tintColor = [UIColor orangeColor];
[[UISlider appearance] setMinimumTrackTintColor:tintColor];
[[CERoundProgressView appearance] setTintColor:tintColor];
self.progressView.trackColor = [UIColor colorWithWhite:0.80 alpha:1.0];
self.progressView.startAngle = (3.0*M_PI)/2.0;
}
- (void)viewDidUnload
{
[self setProgressView:nil];
[self setProgressSlider:nil];
[self setPlayPauseButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[progressView release];
[progressSlider release];
self.player = nil;
[playPauseButton release];
[super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)progressSlider:(UISlider *)sender
{
self.player.position = sender.value;
self.progressView.progress = sender.value;
}
- (IBAction)playPauseButton:(UIButton *)sender
{
if(sender.selected) // Shows the Pause symbol
{
sender.selected = NO;
[self.player pause];
}
else // Shows the Play symbol
{
sender.selected = YES;
[self.player play];
}
}
// MARK: CEPlayerDelegate methods
- (void) player:(CEPlayer *)player didReachPosition:(float)position
{
self.progressView.progress = position;
self.progressSlider.value = position;
}
- (void) playerDidStop:(CEPlayer *)player
{
self.playPauseButton.selected = NO;
self.progressView.progress = 0.0;
self.progressSlider.value = 0.0;
}
#end
where should I make change to get my desired output, help please
Try this, replace otherColor with your 2nd half color. You may have to fix some syntax errors, my version of Xcode wont run on this computer so I couldn't check.
#import "CEViewController.h"
#interface CEViewController ()
{
UIColor *progressColor;
BOOL colorChanged;
}
#end
#implementation CEViewController
#synthesize progressView;
#synthesize progressSlider;
#synthesize playPauseButton;
#synthesize player;
#synthesize progressColor;
#synthesize colorChanged;
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.player = [[[CEPlayer alloc] init] autorelease];
self.player.delegate = self;
self.progressColor= [UIColor orangeColor];
[[UISlider appearance] setMinimumTrackTintColor:self.progressColor];
[[CERoundProgressView appearance] setTintColor:self.progressColor];
self.progressView.trackColor = [UIColor colorWithWhite:0.80 alpha:1.0];
self.progressView.startAngle = (3.0*M_PI)/2.0;
colorChanged = false;
}
- (void)viewDidUnload
{
[self setProgressView:nil];
[self setProgressSlider:nil];
[self setPlayPauseButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (void)dealloc {
[progressView release];
[progressSlider release];
self.player = nil;
[playPauseButton release];
[super dealloc];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (IBAction)progressSlider:(UISlider *)sender
{
self.player.position = sender.value;
if(sender.value >= 0.5 && colorChanged == false) {
self.progressColor= [UIColor otherColor];
[[UISlider appearance] setMinimumTrackTintColor:self.progressColor];
[[CERoundProgressView appearance] setTintColor:self.progressColor];
colorChanged = true;
}
self.progressView.progress = sender.value;
}
- (IBAction)playPauseButton:(UIButton *)sender
{
if(sender.selected) // Shows the Pause symbol
{
sender.selected = NO;
[self.player pause];
}
else // Shows the Play symbol
{
sender.selected = YES;
[self.player play];
}
}
// MARK: CEPlayerDelegate methods
- (void) player:(CEPlayer *)player didReachPosition:(float)position
{
self.progressView.progress = position;
self.progressSlider.value = position;
}
- (void) playerDidStop:(CEPlayer *)player
{
self.playPauseButton.selected = NO;
self.progressView.progress = 0.0;
self.progressSlider.value = 0.0;
}
#end

AVAudioPlayer is playing again without being called play.

I have 2 views and video player and an audio player. when button on the first view is pressed. then audio and a video player start playing. And after the movie has stopped playing. next view is appear. when i press back button on the second view same audio is playing. Dont know where to start
- (id) init {
if (self = [super init]) {
movieName = #"03";
self.view = [[[OtsugeView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
}
return self;
}
- (void) toNext {
NSLog(#"OtsugeViewController:toNext");
[self.navigationController popViewControllerAnimated:NO];
}
- (void) toToppage
{
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
[self.navigationController popToRootViewControllerAnimated:NO];
}
- (void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
NSLog(#"Screen touch Otsuge View");
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:nil
delegate:self
cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Retry", #"Main Menu", nil];
actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
actionSheet.cancelButtonIndex = 0;
[actionSheet showInView:self.view]; // show from our table view (pops up in the middle of the table)
[actionSheet release];
}
- (void) actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex: (NSInteger)buttonIndex
{
switch (buttonIndex) {
case 0: // Retry
[self presentModalViewController:mMoviePlayer animated:YES];
[self play];
break;
case 1: // Main Menu
[self toToppage];
break;
case 2: // Cancel
break;
default:
break;
}
}
- (void) viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
mMoviePlayer.moviePlayer.backgroundView.backgroundColor = [UIColor blackColor];
[self playSound:#"taiko_1"];
[(OtsugeView *)self.view renewImageView];
}
- (void) viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}
- (void) dealloc {
[super dealloc];
}
#end
and the movieplayerclass is
- (NSURL *)createURL
{
NSURL *mvURL;
NSBundle *bundle = [NSBundle mainBundle];
if (movieName != nil) {
if (bundle) {
NSString *mvPath = [bundle pathForResource:movieName ofType:#"m4v"];
if (mvPath) {
mvURL = [NSURL fileURLWithPath:mvPath];
}
}
}
return mvURL;
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag {
[aAudioPlayer setDelegate:nil];
[aAudioPlayer release];
NSLog(#"MovieViewController:audioHasFinished");
NSLog(#"%#", aAudioPlayer.url);
}
- (void)playSound:(NSString *)file {
NSURL *avURL;
NSString *avPath = [[NSBundle mainBundle] pathForResource:file ofType:#"m4a"];
if (avPath) {
avURL = [NSURL fileURLWithPath:avPath];
aAudioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:avURL error:nil];
[aAudioPlayer setDelegate:self];
[aAudioPlayer play];
NSLog(#"MovieViewController:playSound");
}
}
- (void)toNext {
// implementation sub classes
NSLog(#"MovieViewController:toNext");
}
- (void) clearVideo{
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:mMoviePlayer.moviePlayer];
[mMoviePlayer release];
mMoviePlayer = nil;
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
NSLog(#"MovieViewController:moviePlaybackDidFinish");
[[UIApplication sharedApplication] setStatusBarHidden:YES withAnimation:NO];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:mMoviePlayer.moviePlayer];
[self dismissModalViewControllerAnimated:YES];
[mMoviePlayer release];
mMoviePlayer = nil;
mPlayerPushed = NO;
[self toNext];
}
- (void) moviePreloadDidFinish : (NSNotification *)notification{
[self prepareFinished];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:mMoviePlayer.moviePlayer];
}
- (void) prepareFinished{
}
- (void) initPlayer{
if (mMoviePlayer != nil) {
[mMoviePlayer release];
}
mMoviePlayer = [[MoviePlayerViewController alloc] initWithContentURL:[self createURL]];
// Added 3.2 versions
[[NSNotificationCenter defaultCenter] removeObserver:mMoviePlayer
name:MPMoviePlayerPlaybackDidFinishNotification object:mMoviePlayer.moviePlayer];
[mMoviePlayer.moviePlayer setShouldAutoplay:NO];
mMoviePlayer.moviePlayer.backgroundView.backgroundColor = [UIColor blackColor];
mMoviePlayer.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
mMoviePlayer.moviePlayer.controlStyle = MPMovieControlStyleNone;
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:mMoviePlayer.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(moviePreloadDidFinish:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:mMoviePlayer.moviePlayer];
mPlayerPushed = YES;
}
- (void) play {
NSLog(#"MovieViewController:play");
[mMoviePlayer.moviePlayer prepareToPlay];
[mMoviePlayer.moviePlayer play];
}
- (void)viewWillAppear:(BOOL) animated {
if (!mMoviePlayer) {
[self initPlayer];
}
[super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)didReceiveMemoryWarning {
NSLog(#"memory error!");
// Releases the view if it doesn't have a superview.
//[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
}
- (void)dealloc {
[nextController release];
[movieName release];
[super dealloc];
}
#end
The problem is in your second block of code:
The - (void) viewWillAppear:(BOOL)animated method has the following line in it:
[self playSound:#"taiko_1"];
This makes it play the sound, every time that the view is shown, including being shown a second time after dismissing a different view controller.
If you only want it to play once, then you need to move it somewhere else like viewDidLoad:
- (void)viewDidLoad {
[super viewDidLoad];
[self playSound:#"taiko_1"];
}

How to get the music files from the library

iam developing one application.In that i need to get the music files from the phone library.For that iam using the MPMediaPickerCOntroller.But it doesn't fire the didpickingitem delegate method.My code like below.
- (void)viewDidLoad
{
[super viewDidLoad];
MPMediaPickerController *picker =[[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = YES;
picker.prompt =#"Add songs to play";
[self presentModalViewController:picker animated: YES];
}
- (void) mediaPicker: (MPMediaPickerController *) mediaPicker didPickMediaItems: (MPMediaItemCollection *) mediaItemCollection
{
NSLog(#"sdfadsf");
NSLog(#"%#",mediaItemCollection);
NSArray *slist=[mediaItemCollection copy];
NSLog(#"%#",slist);
}
Do you declare the MPMediaPickerControllerDelegate in your .h?
ex:
#interface FirstViewController : UIViewController
If you do not that would explain why the method isn't firing. Also, I do not believe it will work on the simulator; only on devices.
EDIT:
-(IBAction)presentLibrary:(id)sender
{
//this is called from a button press, but you could do it in viewDidLoad
MPMediaPickerController *picker = [[MPMediaPickerController alloc] initWithMediaTypes: MPMediaTypeMusic];
picker.delegate = self;
picker.allowsPickingMultipleItems = NO;
picker.prompt = NSLocalizedString (#"Select any song from the list", #"Prompt to user to choose some songs to play");
[self presentModalViewController: picker animated: YES];
}
- (void)mediaPicker:(MPMediaPickerController *)mediaPicker didPickMediaItems:(MPMediaItemCollection *)mediaItemCollection
{
NSLog(#"didpick");
if (mediaItemCollection) {
[_mediaPlayer setQueueWithItemCollection: mediaItemCollection];
_mediaCollection = mediaItemCollection;
}
[mediaPicker dismissModalViewControllerAnimated:YES];
}
Read from here The Music Player Framework in iPhone

UIButton is dead after I change views and switch back

So I created a program where a sound occurs when the device is shaken. Theres a button, that when tapped stops the sound from being played at any time (This is the "reset" method). There's another button, that when pushed displays another view (This is the "infoView" method). The problem occurs when I go the "infoView" then go back to the first view. The sound still play when the device is shaken but the "reset" button becomes unresponsive. Here's what I have so far, any help would be appreciated.
PS. I'm wondering if it has anything to do with FirstResponders? I'm still trying to wrap my head around FirstResponders.
The .h
#import <UIKit/UIKit.h>
#import "AVfoundation/AVfoundation.h"
#interface OldTvViewController : UIViewController{
AVAudioPlayer *audioPlayer;
}
-(IBAction)reset;
-(IBAction)infoView:(id)sender;
#end
the .m
#import "OldTvViewController.h"
#import "AudioToolBox/AudioToolBox.h"
#import "infoViewController.h"
#implementation OldTvViewController
-(IBAction)infoView:(id)sender{
infoViewController *second = [[infoViewController alloc] initWithNibName:Nil bundle:Nil];
[self presentModalViewController:second animated:YES];
[second release];
}
-(BOOL) canBecomeFirstResponder{
return YES;
}
-(void)motionBegan:(UIEventSubtype)motion withEvent:(UIEvent *)event{
if (event.subtype == UIEventSubtypeMotionShake) {
//Play throw sound
if(audioPlayer.playing){
[audioPlayer stop];
} else{
NSURL *url = [NSURL fileURLWithPath:[NSString stringWithFormat:#"%#/bomb.mp3",[[NSBundle mainBundle] resourcePath]]];
NSError *error;
audioPlayer = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:&error];
audioPlayer.numberOfLoops = 0;
[audioPlayer play];
}
}
}
-(IBAction)reset{
[audioPlayer stop];
}
-(void)viewDidAppear:(BOOL)animated{
[self becomeFirstResponder];
[super viewDidAppear:animated];
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
#end
when You go to info view then where your all button available in that class you try this code.
-(void)viewWillDisapeers
{
[audioPlayer stop];
}
or add in this method
-(IBAction)infoView:(id)sender
{
infoViewController *second = [[infoViewController alloc] initWithNibName:Nil bundle:Nil];
[self presentModalViewController:second animated:YES];
[audioPlayer stop];
[second release];
}

MPMoviePlayer Bad-Access error after playing video

I´ve created an new ViewController (only with the .h and .m file) and added that code to play a video. After the video has finished, i get a "Exe_bad_access" error.
Error message when adding "NSZombieEnabled=true" to the excecutable as a argument:
"TestPlayingVideo[654:207]
-[MPMoviePlayerController stop]: message sent to deallocated instance
0x63042d0"
Whats wrong with that? How can i do correct memory management when playing video?
#import "TestPlayingVideoViewController.h"
#import <MediaPlayer/MediaPlayer.h>
#implementation TestPlayingVideoViewController
- (void)viewDidLoad {
[super viewDidLoad];
[self.view setBackgroundColor:[UIColor darkGrayColor]];
UIButton* btn = [[UIButton alloc] initWithFrame:CGRectMake(50 , 50, 200, 25)];
[btn setTitle:#"press me" forState:UIControlStateNormal];
[btn addTarget:self action:#selector(action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:btn];
[btn release];
}
- (void)action:(id)sender
{
NSLog(#"UIButton was clicked");
NSString *url = [[NSBundle mainBundle] pathForResource:#"mymovie" ofType:#"m4v"];
MPMoviePlayerViewController* moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url] ];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(moviePlayBackComplete:) name:MPMoviePlayerPlaybackDidFinishNotification object:moviePlayerController.moviePlayer];
[moviePlayerController.moviePlayer play];
//[self.view addSubview:moviePlayerController.view];
[self presentMoviePlayerViewControllerAnimated:moviePlayerController];
}
- (void) moviePlayBackComplete:(NSNotification*) notification {
MPMoviePlayerController* player = [notification object];
[[NSNotificationCenter defaultCenter] removeObserver:self name:MPMoviePlayerPlaybackDidFinishNotification object:player];
[self dismissMoviePlayerViewControllerAnimated];
[player stop];
//[self.view removeFromSuperView];
[player release];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
return YES;
}
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[super dealloc];
}
#end
There's a lot of confusion here over what you're releasing: for example, here's your main alloc of your movie player:
MPMoviePlayerViewController* moviePlayerController = [[MPMoviePlayerViewController alloc] initWithContentURL:[NSURL fileURLWithPath:url] ];
But what you are releasing isn't this moviePlayerController - you're only releasing the .moviePlayer property of your MPMoviePlayerController. Notice when you create your NSNotification you're passing moviePlayerController.moviePlayer, not simply moviePlayerController.
So you're not releasing your moviePlayerController, you're in fact attempting to release a property of that object. Which you shouldn't do - you should release the object, and let it worry about releasing its properties.