SoloAmbient和applicationDidEnterBackground

时间:2012-03-06 14:44:45

标签: iphone objective-c ios xcode avaudiosession

我想在应用程序转到后台后设置SoloAmbient(并在iPhone中静音所有音乐)。

我写了这样的代码,但它不起作用

MyAppDelegate.h

@interface MyAppDelegate : UIResponder <UIApplicationDelegate> {
AVAudioSession *audioSession;
}
@property (strong, nonatomic) AVAudioSession *audioSession;

MyAppDelegate.m

- (void)applicationDidEnterBackground:(UIApplication *)application {
NSLog(@"Application entered background state.");

//[self.DelcloseSession setCategory:AVAudioSessionCategorySoloAmbient error:nil];  
//[self.DelcloseSession setActive:YES error:nil];

audioSession = [AVAudioSession sharedInstance];
[audioSession setDelegate:self];

NSError *averr = nil;
[audioSession setCategory:AVAudioSessionCategoryPlayback error:&averr]; 
if(averr)
{
    NSLog(@"audioSession: %@ %d %@", [averr domain], [averr code], [[averr userInfo] description]);
}

averr = nil;
[audioSession setActive:YES error:&averr];
if(averr)
{
    NSLog(@"audioSession: %@ %d %@", [averr domain], [averr code], [[averr userInfo] description]);
}

averr = nil;
[audioSession setCategory:AVAudioSessionCategorySoloAmbient error:&averr];
if(averr)
{
    NSLog(@"audioSession: %@ %d %@", [averr domain], [averr code], [[averr userInfo] description]);
}   

实际应用程序向我发送日志“audioSession:NSOSStatusErrorDomain 560161140(null)”,iPhone上的音乐(来自iPod或其他应用程序)仍在播放。

如何解决?该怎么做,当应用程序进入后台时它会打开SoloAmbient并使所有内容静音?也许还有其他机会睡觉吗?

2 个答案:

答案 0 :(得分:0)

您的应用需要在其背景模式plist中设置音频背景,设置音频会话并开始播放声音(静音等),然后才能退出活动状态并进入后台。否则,音频会话属于新的前台应用程序。

答案 1 :(得分:0)

您可以使用媒体播放器框架

检测iPod播放状态
#import <MediaPlayer/MediaPlayer.h>

然后这个

if ([[MPMusicPlayerController iPodMusicPlayer] playbackState] == MPMusicPlaybackStatePlaying) {
    //iPod is playing
} else {
    //iPod is not playing
}

从那里开始

相关问题