Forcing audio playback through iPhone speaker using Swift

I have an application that records and then plays an audio file. Currently, sound is played through the speaker speaker. Can someone tell me how Swift will handle the encoding to make the sound go out of the speaker?

The following is one example that I use to play an audio file:

@IBAction func playAudioVader(sender: UIButton) { playAudioWithVariablePitch(-1000) } func playAudioWithVariablePitch(pitch: Float){ audioPlayer.stop() audioEngine.stop() audioEngine.reset() var audioPlayerNode = AVAudioPlayerNode() audioEngine.attachNode(audioPlayerNode) var changePitchEffect = AVAudioUnitTimePitch() changePitchEffect.pitch = pitch audioEngine.attachNode(changePitchEffect) audioEngine.connect(audioPlayerNode, to: changePitchEffect, format: nil) audioEngine.connect(changePitchEffect, to: audioEngine.outputNode, format: nil) audioPlayerNode.scheduleFile(audioFile, atTime: nil, completionHandler: nil) audioEngine.startAndReturnError(nil) audioPlayerNode.play() } override func viewDidLoad() { super.viewDidLoad() audioPlayer = AVAudioPlayer(contentsOfURL:receivedAudio.filePathURL, error: nil) audioPlayer.enableRate = true audioEngine = AVAudioEngine() audioFile = AVAudioFile(forReading:receivedAudio.filePathURL, error: nil) } 
+7
xcode ios8 swift avaudioplayer
source share
2 answers

EDIT July 2017: See the Husam answer for Swift 2.0.

With Swift 1.2, you use overrideOutputAudioPort and AVAudioSessionPortOverride. It can be implemented by doing something like this:

 if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error:&error) { println("could not set output to speaker") if let e = error { println(e.localizedDescription) } } 

I am working on an application that uses this now, and I have a function called setSessionPlayandRecord that looks like this:

 func setSessionPlayAndRecord() { let session:AVAudioSession = AVAudioSession.sharedInstance() var error: NSError? if !session.setCategory(AVAudioSessionCategoryPlayAndRecord, error:&error) { println("could not set session category") if let e = error { println(e.localizedDescription) } } if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker, error:&error) { println("could not set output to speaker") if let e = error { println(e.localizedDescription) } } if !session.setActive(true, error: &error) { println("could not make session active") if let e = error { println(e.localizedDescription) } } } 
+11
source share

Swift 2.0 Code

 func setSessionPlayerOn() { do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord) } catch _ { } do { try AVAudioSession.sharedInstance().setActive(true) } catch _ { } do { try AVAudioSession.sharedInstance().overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker) } catch _ { } } func setSessionPlayerOff() { do { try AVAudioSession.sharedInstance().setActive(false) } catch _ { } } 
+11
source share

All Articles