我想我已经在我以前的应用程序之一做之前。认为您需要在应用程序启动后立即配置音频会话。
下面是一段代码,显示如何做到这一点。但它用Objective C.
- (void) initializeAudioSession
{
// Registers this class as the delegate of the audio session to listen for audio interruptions
[[NSNotificationCenter defaultCenter] addObserver: self
selector: @selector(audioRouteChanged:)
name: AVAudioSessionRouteChangeNotification
object: [AVAudioSession sharedInstance]];
//Set the audio category of this app to playback (allows music to play in background)
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategorySoloAmbient error: &setCategoryError];
if (setCategoryError) {
//RESPOND APPROPRIATELY
NSLog(@"AVAudioSession error: %@", setCategoryError);
}
// An instance of the audio player/manager is passed to the listener
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(audioRouteChanged:) name:AVAudioSessionRouteChangeNotification object:nil];
//Activate the audio session
NSError *activationError = nil;
[[AVAudioSession sharedInstance] setActive: YES error: &activationError];
if (activationError) {
//RESPOND APPROPRIATELY
NSLog(@"AVAudioSession error: %@", activationError);
}
}
#pragma mark -
#pragma mark Audio session callbacks
-(void)audioRouteChanged:(NSNotification*)audioChanged;
{
NSDictionary *userInfo = [audioChanged userInfo];
int routeChangeReason = (int)[userInfo objectForKey:AVAudioSessionRouteChangeReasonKey];
if ([SpotifyPlayer sharedPlayer].isPlaying) {
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
{
[[SpotifyPlayer sharedPlayer] setIsPlaying:false callback:nil];
}
}
}
void audioRouteChangeListenerCallback (void *inUserData, AudioSessionPropertyID inPropertyID, UInt32 inPropertyValueSize, const void *inPropertyValue)
{
if (inPropertyID != kAudioSessionProperty_AudioRouteChange) return;
CFDictionaryRef routeChangeDictionary = inPropertyValue;
CFNumberRef routeChangeReasonRef = CFDictionaryGetValue (routeChangeDictionary, CFSTR (kAudioSession_AudioRouteChangeKey_Reason));
SInt32 routeChangeReason;
CFNumberGetValue (routeChangeReasonRef, kCFNumberSInt32Type, &routeChangeReason);
// "Old device unavailable" indicates that a headset was unplugged, or that the
// device was removed from a dock connector that supports audio output.
if (routeChangeReason == kAudioSessionRouteChangeReason_OldDeviceUnavailable)
{
[[SpotifyPlayer sharedPlayer] setIsPlaying:false callback:nil];
}
}
感谢您的回答基督徒。我只是想知道为什么当Spotify的示例项目中没有任何地方使用背景音频时,所有这些都是必需的? –
@ja你确定它没有做任何事情吗?你指的是哪个例子? – christian
我指的是包含在SDK下载中的示例项目。事实证明,他们确实有激活AVAudioSession的东西,虽然为什么它不是默认行为的一部分,似乎让我感到困惑 –