Source

AirPlayStreaming / AirplaySelection / JKAppDelegate.m

Full commit
//
//  JKAppDelegate.m
//  AirplaySelection
//
//  Created by Joris Kluivers on 7/11/12.
//  Copyright (c) 2012 Joris Kluivers. All rights reserved.
//

#import "JKAppDelegate.h"

#import <CoreAudio/CoreAudio.h>
#import <AVFoundation/AVFoundation.h>

#import "JKAudioManager.h"
#import "JKAudioDevice.h"
#import "JKAudioSource.h"

#import "JKAudioPlayer.h"

struct Device {
	char mName[64];
	AudioDeviceID mID;
};

@interface JKAppDelegate ()
@property(nonatomic, strong) JKAudioPlayer *player;
@end

static NSInteger staticMenuItemCount = 2;

@implementation JKAppDelegate

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
	NSURL *fileURL = [[NSBundle mainBundle] URLForResource:@"audio" withExtension:@"m4a"];
	
	self.player = [[JKAudioPlayer alloc] initWithURL:fileURL];
	
	return;
}

- (IBAction) toggle:(id)sender {
	if ([self.player isPlaying]) {
		[self.player pause];
		[self.toggleButton setTitle:@"Start"];
	} else {
		[self.player play];
		[self.toggleButton setTitle:@"Stop"];
	}
}

- (NSArray *) airplaySources {
	NSMutableArray *sources = [NSMutableArray array];
	
	NSArray *devices = [[JKAudioManager sharedManager] outputDevices];
	
	for (JKAudioDevice *device in devices) {
		if (device.isAirplay) {
			[sources addObjectsFromArray:[device audioSources]];
		}
	}
	
	return sources;
}

- (IBAction) outputSourceSelectionChange:(id)sender {
	NSInteger selectedIndex = [((NSPopUpButton *)sender) indexOfSelectedItem];
	
	if (selectedIndex < staticMenuItemCount) {
		// reset to default output device
		
		return;
	}
	
	selectedIndex -= staticMenuItemCount;
	
	// changing audio devices throws error if still playing
	[self.player pause];
	
	JKAudioSource *newlySelectedSource = [[self airplaySources] objectAtIndex:selectedIndex];
	JKAudioDevice *device = newlySelectedSource.device;
	
	[device setAudioSource:newlySelectedSource];
	[self.player setOutputAudioDevice:device.identifier];
	
	[self.player play];
}

- (IBAction) selectAllSources:(id)sender {
	NSArray *sources = [self airplaySources];
	
	if ([sources count] < 1) {
		return;
	}
	
	[self.player pause];
	
	JKAudioSource *firstSource = [sources objectAtIndex:0];
	JKAudioDevice *airplayDevice = firstSource.device;
	
	[airplayDevice setAudioSources:sources];
	[self.player setOutputAudioDevice:airplayDevice.identifier];
	
	[self.player play];
}

@end