我有一个应用程序记录然后播放音频文件。目前,音频播放通过耳机扬声器播放。有人能告诉我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)
}
答案 0 :(得分:11)
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)
}
}
我正在开发一个现在使用它的应用程序,我有一个名为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)
}
}
}
答案 1 :(得分:11)
Swift 2.0 代码
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 _ {
}
}