Skip to content

Instantly share code, notes, and snippets.

@jumbo-in-Jap
Created August 7, 2017 05:52
Show Gist options
  • Save jumbo-in-Jap/7b4ee398c489c0072cf756720881dad5 to your computer and use it in GitHub Desktop.
Save jumbo-in-Jap/7b4ee398c489c0072cf756720881dad5 to your computer and use it in GitHub Desktop.
スピーカーの出力先を変える
// 出力先判定
static func IsHeadSetConnected() -> Bool{
let route = AVAudioSession.sharedInstance().currentRoute;
for desc in route.outputs
{
let portType = desc.portType;
if (portType == AVAudioSessionPortHeadphones)
{
return true;
}
}
return false;
}
// イヤホンが刺された、出された時に呼ばれる
func setAudioNotification(){
NotificationCenter.default.addObserver(self,
selector: #selector(self.didChangeAudioSessionRoute(notification:)),
name: NSNotification.Name.AVAudioSessionRouteChange,
object: nil)
}
func didChangeAudioSessionRoute(notification:Notification){
for desc in AVAudioSession.sharedInstance().currentRoute.outputs{
if desc.portType == AVAudioSessionPortHeadphones{
// イヤホン刺さった
}else{
// イヤホン抜けた
if !self.isSetSpeeker{
self.setupSpeeker()
}
}
}
}
// 変える実装
DispatchQueue.main.asyncAfter(deadline: .now() + 1.0) {
do{
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
try audioSession.setMode(AVAudioSessionModeVideoChat)
try audioSession.overrideOutputAudioPort(AVAudioSessionPortOverride.speaker)
try audioSession.setActive(true)
}catch let error as NSError{
DDLogError("Lesson \(error)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment