Control non iPod music players (such as Spotify) from within iOS app - objective-c

In my app I need to pause and restart background music while I play my own sound.
The approach for the iPod is to use:
[[MPMusicPlayerController iPodMusicPlayer] pause];
and :
[[MPMusicPlayerController iPodMusicPlayer] play];
For non iPod apps this has no affect.
Second attempt is to enable ducking:
UInt32 property = sender.on;
AudioSessionSetProperty(kAudioSessionProperty_OtherMixableAudioShouldDuck,sizeof(property),&property);
AudioSessionSetActive(property);
Also works for iPod music player, not Spotify.
Setting kAudioSessionCategory_SoloAmbientSound does stop all music but doesn't restart it.

The way to control this is using AVAudioSession's setActive method.
When you want to play your sound, set your session to be active:
[[AVAudioSession sharedInstance] setActive:YES error:nil];
When you stop playing, then set your session to inactive but with the flag to notify others as well. This flag should cause the other app to restart (should work for iPod and others). For iOS6+ with AVAudioSession you could do this:
[[AVAudioSession sharedInstance] setActive:NO withOptions:AVAudioSessionSetActiveOptionNotifyOthersonDeactivation error:nil];
Pre iOS 6:
[[AVAudioSession sharedInstance] setActive:NO withFlags:AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation error:nil];

You don't need too. iOS only allows one application to be playing audio at a time and will automatically pause a music player so that you can play your music, as your app has music playing priority. Just play yours, and let iOS deal with it.

Related

iOS 9 is 'Picture In Picture' mode available with 'Requires Fullscreen' set to YES?

I have an app that requires fullscreen, but want to make Picture In Picture feature available when user opens video playback modal controller (My own player written with AVFoundation).
I have 'app requires fullscreen' flag set to YES in settings.
Can I use Picture in Picture mode for video playback while all my app requires to be fullscreen?
I've created a sample project and found that YES, Picture In Picture feature doesn't depend whether your app needs fullscreen or not.
Maybe this would be helpful for those who are looking for the same question as I did.
Set base SDK version to latest (9.0)
Set "App requires fullscreen" flag in the project settings
Set AVAudioSession category to AVAudioSessionCategoryPlayback in application:didFinishLaunchingWithOptions:
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
Just created AVPlayerViewController and presented it from my root controller
AVPlayerViewController *moviePlayerController = [[AVPlayerViewController alloc] init];
AVPlayer *player = [AVPlayer playerWithURL:[NSURL URLWithString:#"http://127.0.0.1:12345/movie.mp4"]];
moviePlayerController.player = player;
[self presentViewController:moviePlayerController animated:YES completion:nil];
PiP button appeared at the bottom right corner of playback controls and it works!
P.S. I may remove the question and answer if it's obvious or too simple and nobody find it useful.

How to stop AVAudioPlayer once we navigate from one view to into other view in iOS8?

I am fresher to iOS. I am using AVFoundation framework for AVAudioPlayer. This is used for running background sound when user enters into application home screen. This background sound should be stopped when it goes to other views and should be enabled when user come back to the home screen again. Below code is working fine in IOS7, when I upgrade to IOS8 background sound continuously playing and doesn’t stop when I go to other views. Kindly help me in this issue.
I am using below code for start and stop the player
NSString *pewPewPath = [[NSBundle mainBundle]pathForResource:#"background" ofType:#"mp3"];
NSURL *pewPewURL = [NSURL fileURLWithPath:pewPewPath];
NSData *data1 = [NSData dataWithContentsOfURL:pewPewURL];
audio = [[AVAudioPlayer alloc] initWithData:data1 error:nil];
audio.volume=8;
[audio play];
Call the [audio stop]; and set nil to the audio instance when you are navigating to another view. And write this code before you call the next view controller.

UIImagePickerController and application background modes

I’m building an application which supports both video playback and recording (not simultaneously, it’s just two separate features it provides). In order to make the videos play after the app enters background and gets back, I had to add an App plays audio item to Required background modes in the plist (I’m using MPMoviePlayerController for playback).
This, however, causes a problem with my video recording (I’m using UIImagePickerController for it). Basically, even after the picker is dismissed (either by the Cancel button or when it’s finished picking media), the app still keeps the audio recording session running.
If I remove the App plays audio item from the plist, the ImagePickerController’s audio session stops misbehaving, but then I can’t resume the playback of MPMoviePlayerViewController on switching to app from background mode.
Is there a way I can customise the handling of the audio session so that both the MPMoviePlayerController and UIImagePickerController can work properly?
yes, there is a way you can customize the handling of the audio session for what you desire: don't try to set the App plays audio setting.
instead, in your AppDelegate code (which is usually in AppDelegate.m from the simple wizard projects provided), supply code in the applicationWillResignActive: method that will stop the playback in your MPMoviePlayerController, and then use applicationDidBecomeActive: to resume the playback at the point at which you paused it if so desired.
this will not only allow the video to be resumed after a temporary pause, but it will allow you to save the state so that the video can be resumed in case the app is removed from memory or in case the user causes it to be quit.
You can scratch the background modes and instead use notifications to pause/resume your player. See UIApplicationDidBecomeActiveNotification and UIApplicationWillResignActiveNotification in the UIApplication class reference.
You can snag some code and see this implemented in this class. Here is some of the relevant code from that class:
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_didBecomeActive:)
name:UIApplicationDidBecomeActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(_willResignActive:)
name:UIApplicationWillResignActiveNotification
object:nil];
- (void) _didBecomeActive:(NSNotification*)notification {
if (_wasPlaying) {
[_movieController play];
}
}
- (void) _willResignActive:(NSNotification*)notification {
_wasPlaying = _movieController.currentPlaybackRate != 0.0;
if (_wasPlaying) {
[_movieController pause];
}
}

quit the application by setting NSTimer?

is their any better way to quit the application programmatically?
recently i made a radio application that have a user setup to set a time using NSTimer for quit the app process ( i mean sleep time). when the time reaches the app should be stop its process and quit.
i used these statements to quit the app when time reaches,
[[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess];
theTimer=[NSTimer scheduledTimerWithTimeInterval:(1.0/1.0) target:self selector:#selector(countTime) userInfo:nil repeats:YES];
counter-=1;
timeLeft.text=[NSString stringWithFormat:#" %d",counter];
if (counter==0.0) {
[theTimer invalidate];
[[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess];
is their any problem by using [[UIApplication sharedApplication] suspend];
[[UIApplication sharedApplication] terminateWithSuccess]; methods
any other better way to quit the app, or at least freeze the app process..
i need help?
Apple will not approve any application that deliberately suspends or terminates itself. You may use only those methods listed in the official documentation, which does not include suspend or terminateWithSuccess.
I've always used exit(0). I suppose that if you have to run code before the app quitting you should call it before exit(0).
Apple discourages the use of exit() because from the user point of view it looks like a crash. But they also say there is no API call to gracefully terminate your app.
If you're looking for a way to terminate your app without the user pressing home, during sleep time, I assume he won't confuse it with a crash, since he won't be paying attention to your app and exit() leaves no crash log.
So, your options are:
Forget this and just beep after some time to remind him to close the app. (terrible!)
Close the app using your private calls and risk Apple's rejection.
Close the app using exit() and stick with POSIX (accepted) calls.
tanq for your replays, so i just forget about quitting my application programatically. next way is to stop playing my MPMoviePlayerController object. got the next level problem
my settings page for sleepTime and music playing pages, both are different viewControllers
so i can't access MPMoviePlayerController object directly in time settings page, so i created a method on music playing page
MPMoviePlayerController *player=[[MPMoviePlayerController alloc]initWithContentURL:[NSURL URLWithString:#"http://www.radioparadise.com/musiclinks/rp_64aac.m3u"]];
[player prepareToPlay];
[player play];
- (IBAction)StopPlay:(id)sender
{
[player stop];
}
so i created an object for music playing page and i called this method from settings page.,
this is my code in settingsPage
#class MusicPlayingPage;
#interface secondView : UIViewController
{
MusicPlayingPage *audio;
}
and called the method in settingsPage
[audio stopPlay];
control reaches correctly to streamingPage, but it seems like player is not stoping play, i can't access any of these player options [player stop]; , [player pause];
any problem for this method in musicPlayingPage
- (IBAction)StopPlay:(id)sender
{
[player stop];
}
sorry if my question is not understandable.

MPMoviePlayerController iOS play audio file issue

Hi all I am using MPMoviePlayerController to play both video (mp4) and audio (mp3) files. I am facing an issue when the view is removed form screen, the audio keeps playing in the background, video is ok. On iOS 4.3 everything works great, but when I switch to iOS5 and attempt to play audio and press back (remove the view) the audio is still pressent in the background. Is there something different in how MPMoviePlayerController handles audio files in 4.3 and 5 ? I am using the same code for playing both video/audio.
moviePlayBackDidFinish method, where I stop the player
[player setInitialPlaybackTime:-1];
[player stop];
player = nil;
[[player view] removeFromSuperview];
[player release];
Any help is appreciated :)
use this code to pause the audio/video in the MPMoviePlayerController
-(void)viewWillDisappear:(BOOL)animated
{
[mediaPlayer pause];
}