質問

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?

役に立ちましたか?

解決

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 :)

他のヒント

You can use one of these audio streamer for play in background

https://github.com/mattgallagher/AudioStreamer

https://github.com/DigitalDJ/AudioStreamer

it might help you.

This is how it works for me.

Add following to you app-info.plist file

<key>UIBackgroundModes</key>
<array>
<string>audio</string>
</array>

Then in application:didFinishLaunchingWithOptions add following

UIBackgroundTaskIdentifier backgroundTask = [application beginBackgroundTaskWithExpirationHandler:^{
     /* just fail if this happens. */
     NSLog(@"BackgroundTask Expiration Handler is called");
     [application endBackgroundTask:backgroundTask];
}];
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top