I want to add a button to send the audio output to the Applle TV. I use below code but it does not work. Can you help what I am doing wrong?
First I change the AVAudioSession category to be AVAudioSessionCategorySoloAmbient (for searching the connected bluetooth devices for iOS 7 and 8, I have to do this.)
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategorySoloAmbient error:&err];
Then I use this method for switching audio to Apple TV
- (BOOL)switchAirPlay:(BOOL)onOrOff
{
NSError* audioError = nil;
BOOL changeResult = NO;
if (onOrOff) {
self.bipAudioSessionManagerDeviceCurrent = Device_AppleTV;
AVAudioSessionPortDescription* airplayPort = [self airplayAudioDevice];
changeResult = [[AVAudioSession sharedInstance] setPreferredInput:airplayPort error:&audioError];
} else {
AVAudioSessionPortDescription* airplayPort = [self airplayAudioDevice];
changeResult = [[AVAudioSession sharedInstance] setPreferredInput:airplayPort error:&audioError];
}
if (audioError) {
DDLogError(@"Apple TV error, audioSession: %@ %zd %@", [audioError domain], [audioError code], [[audioError userInfo] description]);
}
if (!changeResult) {
DDLogError(@"Apple TV error, audioSession: %@ %zd %@", [audioError domain], [audioError code], [[audioError userInfo] description]);
}
return changeResult;
}
- (AVAudioSessionPortDescription*)airplayAudioDevice {
NSArray* builtinRoutes = @[AVAudioSessionPortAirPlay];
return [self audioDeviceFromTypes:builtinRoutes];
}
- (AVAudioSessionPortDescription*)audioDeviceFromTypes:(NSArray*)types {
NSArray* routes = [[AVAudioSession sharedInstance] availableInputs];
for (AVAudioSessionPortDescription* route in routes) {
if ([types containsObject:route.portType]) {
return route;
}
}
return nil;
}
Edit 1:
According to the documentation in https://developer.apple.com/library/ios/documentation/Audio/Conceptual/AudioSessionProgrammingGuide/AudioSessionBasics/AudioSessionBasics.html the AVAudioSessionCategoryAmbient category supports AirPlay.
Edit 2:
NSArray *inputs = [[AVAudioSession sharedInstance] availableInputs];
Size of the inputs is 1 although iphone is connected to he Apple TV. I don't understand why size is not equal to 2.