Search code examples
iphonecocoa-touchbackground-application

playing radio in background


I just need to confirm if an iPhone app can play or stream radio in the background.

I created a radio app which is working fine.

I want to add a feature by which the user can play radio in a background process, i.e. they don't have to keep the application open to play the radio.

They can close the app, and the radio is still playing.

I read a long time back that Apple has a private API by which an app can run radio in the background, but since it is private, I can't use it.

Any suggestions?


Solution

  • iOS SDK should be above 4.0; first in your delegate codes:

    - (void)applicationDidEnterBackground:(UIApplication *)application {
    
        if (isAbove4_0)
    
     {
    
            CTCallCenter *_center = [[CTCallCenter alloc] init];
    
            _center.callEventHandler = ^(CTCall *call) 
           {
    
                //NSLog(@"call:%@", call.callState);
                if ([call.callState isEqualToString:CTCallStateIncoming]) 
    
                    {
    
                    [RadioPlayer pausePlayer];
    
            }           
        };
        }
    
    }
    

    then, I used MPMoviePlayerController, and AVPlayer is OK;

    if (isAbove4_0) {
        if (_mpmovieplayer == nil) {
            _mpmovieplayer = [[MPMoviePlayerController alloc] initWithContentURL:url];
            [_mpmovieplayer setMovieControlMode:MPMovieControlModeHidden];
        }
    
        [_mpmovieplayer setContentURL:url];
        [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:nil];
        [[AVAudioSession sharedInstance] setActive: YES error: nil];
        // This is necessary if you want to play a sequence of songs, otherwise your app will be
        // killed after the first one finishes.
        [[UIApplication sharedApplication] beginReceivingRemoteControlEvents];
    
        UIBackgroundTaskIdentifier newTaskId = UIBackgroundTaskInvalid;
    
        [_mpmovieplayer play];
    
        newTaskId = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:NULL];
        if (newTaskId != UIBackgroundTaskInvalid && bgTaskId != UIBackgroundTaskInvalid)
            [[UIApplication sharedApplication] endBackgroundTask: bgTaskId];
        bgTaskId = newTaskId;
    
    }
    

    PS:my english is poor, I hope this could be helpful to you :)