AVAudioPlayer后台任务不能正常工作[iOS]

时间:2012-04-24 08:11:59

标签: iphone ios audio background avaudioplayer

我已经尝试了一切:

-setup info.plist     所需的背景模式:App播放音频;

-setup player:

 [[AVAudioSession sharedInstance] setDelegate: self];

// allow app continue to play when the screen is locked
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback
                                       error:nil];

UInt32 doSetProperty = 0;
AudioSessionSetProperty ( kAudioSessionProperty_OverrideCategoryMixWithOthers,
                         sizeof (doSetProperty),
                         &doSetProperty
                         );

// Registers the audio route change listener callback function
AudioSessionAddPropertyListener (
                                 kAudioSessionProperty_AudioRouteChange,
                                 audioRouteChangeListenerCallback,
                                 self
                                 );

// Activates the audio session.

NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];

[appSoundPlayer prepareToPlay];
[appSoundPlayer setVolume: 1.0];
[appSoundPlayer setDelegate: self];
[[UIApplication sharedApplication] beginReceivingRemoteControlEvents];

我忘记了什么?有什么不对吗?

1 个答案:

答案 0 :(得分:1)

您需要将音频类别设置为播放:

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback error:&error];

如果您希望允许将音频与其他应用混音,可以添加此选项,只需确保 之前将音频会话设置为有效。

[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayback withOptions:AVAudioSessionCategoryOptionMixWithOthers error:nil];

现在您可以将音频会话设置为活动状态:

[[AVAudioSession sharedInstance] setActive:YES error:&error];