Wednesday, June 5, 2013

AVAudioPlayer channelAssignments example in Objective C (iOS).


AVAudioPlayer channelAssignments

An array of AVAudioSessionChannelDescription objects associated with the audio player

@property(nonatomic, copy) NSArray* channelAssignments

Discussion of [AVAudioPlayer channelAssignments]
The default value for this property is nil. When non-nil, this array must have the same number of elements as returned by the numberOfChannels property. You can use this property to help you assign output to play to different channels.

AVAudioPlayer channelAssignments example.
- (void)viewDidLoad
{
    [super viewDidLoad];
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleRouteChange:) name:AVAudioSessionRouteChangeNotification object:session];
    NSError *err = nil;
    [session setCategory:AVAudioSessionCategoryMultiRoute error:&err];
    [session setActive:YES error:&err];
    AVAudioSessionRouteDescription *route = [session currentRoute];
    NSArray *outputs = [route outputs];
    NSString *soundFilePath = [[NSBundle mainBundle] pathForResource:@"gotospeaker1" ofType:@"wav"];
    NSURL *soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    self.player1 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];

    soundFilePath = [[NSBundle mainBundle] pathForResource:@"gotobluetoothspeaker1" ofType:@"mp3"];
    soundFileURL = [NSURL fileURLWithPath:soundFilePath];
    self.player2 = [[AVAudioPlayer alloc] initWithContentsOfURL:soundFileURL error:nil];

    AVAudioSessionChannelDescription *desiredChannel1 = [[[outputs objectAtIndex:0] channels] objectAtIndex:0];
    NSArray *channelDescription = [NSArray arrayWithObjects:desiredChannel1,nil];
    self.player1.channelAssignments = channelDescription;
}

- (void)handleRouteChange:(NSNotification*)notification
{
    NSArray *outputs = [[notification.userInfo valueForKey:AVAudioSessionRouteChangePreviousRouteKey] outputs];
    AVAudioSessionChannelDescription *desiredChannel = [[[outputs objectAtIndex:0] channels] objectAtIndex:0];
    NSArray *channelDescription = [NSArray arrayWithObject:desiredChannel];
    self.player2.channelAssignments = channelDescription;
}

End of AVAudioPlayer channelAssignments example article.