iOS イヤホンジャックに機器を接続した状態で本体の内蔵スピーカーから音を鳴らす
イヤホンジャックに差し込むタイプの機器(カードリーダー等)を接続した状態で、
本体の内蔵イヤホンから音を鳴らす方法をメモっておきます。
概要
通常はPortをイヤホン側(機器側)に向けておく
音を鳴らすときだけ内蔵スピーカー側に向ける
音の再生が終わったらイヤホン側に戻す
SampleViewController.h
#import <UIKit/UIKit.h>
#import <AVFoundation/AVFoundation.h>
@interface SampleViewController : UIViewController <AVAudioPlayerDelegate>
@end
SampleViewController.m
#import "SampleViewController.h"
#import <AVFoundation/AVAudioSession.h>
#import <AudioToolbox/AudioServices.h>
@interface SampleViewController ()
{
AVAudioPlayer *player;
}
@end
@implementation SampleViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.
// overrideOutputAudioPort:でAVAudioSessionPortOverrideSpeakerを設定するための準備
[[AVAudioSession sharedInstance] setCategory:AVAudioSessionCategoryPlayAndRecord error:nil];
// AudioSessionを有効化
[[AVAudioSession sharedInstance] setActive:YES error:nil];
// 電話が鳴るなどAudioSessionの割り込み発生時の処理を登録
NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
[center addObserver:self selector:@selector(sessionDidInterrupt:) name:AVAudioSessionInterruptionNotification object:nil];
// 鳴らす音の準備
NSString* path = path = [[NSBundle mainBundle] pathForResource:@"test" ofType:@"aiff"];
NSURL* url = [NSURL fileURLWithPath:path];
player = [[AVAudioPlayer alloc] initWithContentsOfURL:url error:nil];
player.delegate = self;
}
// AudioSessionの割り込み発生時の処理
- (void)sessionDidInterrupt:(NSNotification *)notification
{
switch ([notification.userInfo[AVAudioSessionInterruptionTypeKey] intValue]) {
case AVAudioSessionInterruptionTypeBegan:
[player stop];
break;
case AVAudioSessionInterruptionTypeEnded:
default:
[[AVAudioSession sharedInstance] setActive:YES error:nil];
break;
}
}
// サウンド再生が終わったときの処理
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)player successfully:(BOOL)flag
{
// 内蔵スピーカーへの強制出力を止める
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideNone error:nil];
}
- (IBAction)sound:(id)sender {
// 内蔵スピーカーへ強制出力
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];
[player play];
}
@end
参考:
iOS でヘッドフォンを差した状態でも、内蔵スピーカーから音を出す方法
iOS6以降のAVAudioSessionのdelegate設定方法