我有一个应用程序记录,然后播放音频文件.目前,通过耳机扬声器播放音频.有人能告诉我
Swift如何处理编码以强制音频输出扬声器吗?
下面是我用来播放音频文件的一个实例:
@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) }@H_502_5@
解决方法
编辑2017年7月:请参阅Husam对Swift 2.0解决方案的回答.
从Swift 1.2开始,您使用overrideOutputAudioPort和AVAudioSessionPortOverride.它可以通过这样的方式实现:
if !session.overrideOutputAudioPort(AVAudioSessionPortOverride.Speaker,error:&error) { println("could not set output to speaker") if let e = error { println(e.localizedDescription) } }@H_502_5@我正在开发一个现在使用它的应用程序,我有一个名为setSessionPlayandRecord的函数,它看起来像:
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) } } }@H_502_5@