Youtubeの再生と本体スピーカー/イヤホンの音の出力先を変更する実装です。
AVAudioSessionのoverrideOutputAudioPortメソッドで値設定することで制御しています。
AVAudioSessionPortOverrideSpeakerを設定すると本体スピーカーからの出力となります。
リファレンスは以下です。
AVAudioSession Class Reference
#import "ViewController.h"
#import <AVFoundation/AVFoundation.h>
#import <AudioToolbox/AudioServices.h>
@interface ViewController ()
@property (nonatomic, strong) UIWebView *webView;
@property (nonatomic, strong) UIButton *loadBtn;
@property (nonatomic, strong) UISwitch *portSwitch;
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
[audioSession setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
[audioSession setActive:YES error:nil];
self.webView = [[UIWebView alloc] initWithFrame:CGRectMake(0, 0, 320, 320)];
[self.view addSubview:self.webView];
self.loadBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
self.loadBtn.frame = CGRectMake(40, 400, 80, 32);
[self.loadBtn setTitle:@"load" forState:UIControlStateNormal];
[self.loadBtn addTarget:self action:@selector(loadBtn_action:) forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:self.loadBtn];
self.portSwitch = [[UISwitch alloc] initWithFrame:CGRectMake(200, 400, 120, 32)];
[self.portSwitch addTarget:self action:@selector(switchValueChanged:) forControlEvents:UIControlEventValueChanged];
[self.view addSubview:self.portSwitch];
}
- (void)loadBtn_action:(UIButton *)sender
{
NSURL *url = [NSURL URLWithString:@"https://www.youtube.com/watch?v=NB_gAf4wP-I"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[self.webView loadRequest:request];
}
- (void)switchValueChanged:(UISwitch *)sender
{
AVAudioSession *audioSession = [AVAudioSession sharedInstance];
if (sender.on) {
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
}
else {
[audioSession overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
}
}
@end
Xcode6.4で作成。
「Single View Application」で新Projectを作りViewController.mに上記を記述。
アプリ起動後、loadボタンでYoutube動画を読み込み再生してみてください。