iPod - Let the native music app to play sound in b

2019-08-18 01:43发布

问题:

I am building an application for iPod. When running it, the native iPod music app should continue play in background, but this is not happening.

I think it might have something to do with the sound that it is played by my app. For playing a short sound at a certain point, I am using AVAudioPlayer. The code looks like this:

NSString *path = [[NSBundle mainBundle] pathForResource:@"sound" ofType:@"mp3"];
        NSLog(@"%@", path);
        player = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfFile:path] error:nil];
        [player prepareToPlay];
        [player play];

Could this interfere with the native music player on iPod? And another thing. In my app, I have integrated AdWhirl and it appears to use AudioToolbox.

Thanks a lot, George

回答1:

You must set up your AVAudioSession to use the Ambient category. This tells the system that your sound should blend with any already playing sound. The best way to do this in iOS 4 is in the app delegate, like this:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
    [[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryAmbient error:nil];
    // ...
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // reactivate audio session
    [[AVAudioSession sharedInstance] setActive: YES error: nil];
}

Read up on Audio Sessions. If your app produces sound, you always want be conscious of and in control of your audio session.