0

在我的应用程序进入后台后,我想设置 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 并使一切静音?也许还有其他机会睡音乐吗?

4

2 回答 2

0

您可以使用 mediaplayer 框架检测 iPod 播放状态

#import <MediaPlayer/MediaPlayer.h>

然后这个

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

然后从那里去

于 2012-03-06T19:26:49.977 回答
0

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

于 2012-03-06T15:04:18.720 回答