Tuesday, June 7, 2016

Select the iOS device or bluetooth audio output with action sheet

While playing a sound file with AVAudioPlayer, the following code may be used to select the audio output between the speaker of an iPhone/iPad or the bluetooth headset in an action sheet:


let buttonOutput = UIButton(frame: CGRectMake(0, 0, 200, 30))
buttonOutput.center = CGPointMake(view.center.x, view.center.y+200)
buttonOutput.setTitle("Output", forState: UIControlState.Normal)
buttonOutput.setTitleColor(UIColor.blueColor(), forState: UIControlState.Normal)
buttonOutput.setTitleColor(UIColor.cyanColor(), forState: UIControlState.Highlighted)
buttonOutput.addTarget(self, action: #selector(buttonOutputPressed), forControlEvents: UIControlEvents.TouchUpInside)

view.addSubview(buttonOutput)

and

func buttonOutputPressed() {
        
    let model = UIDevice.currentDevice().model
        
    let session = AVAudioSession()
        
    let controller = UIAlertController(title: "Select Output", message: "", preferredStyle: UIAlertControllerStyle.ActionSheet)
        controller.addAction(UIAlertAction(title: model, style: UIAlertActionStyle.Default, handler: { action in
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.DefaultToSpeaker)
    } catch {
        print("AVAudioSession error!")
    }
    }))
    controller.addAction(UIAlertAction(title: "Bluetooth", style: UIAlertActionStyle.Default, handler: { action in
    do {
        try session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: AVAudioSessionCategoryOptions.AllowBluetooth)
    } catch {
        print("AVAudioSession error!")
    }
    }))
    presentViewController(controller, animated: true, completion: nil)
}

Result:



4 comments:

  1. This solved a big problem I was having for days. Thanks, obrigado, gracias, merci, danke schon, arigato...

    ReplyDelete
  2. how to select specific bluetooth route if device is paired with multiple bluetooth devices in action sheet.

    ReplyDelete