我想我已經在我以前的應用程序之一做之前。認爲您需要在應用程序啓動後立即配置音頻會話。
下面是一段代碼,顯示如何做到這一點。但它用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的東西,雖然爲什麼它不是默認行爲的一部分,似乎讓我感到困惑 –