如何在swift中将我的音频会话默认行为设置为播放?

时间:2015-08-01 19:33:23

标签: ios iphone swift audio

我的应用有一个"点击"声音功能。

import AVFoundation

然后以下函数运行" Click"音:

var audioPlayer = AVAudioPlayer()

func playSound() {
    var soundPath = NSBundle.mainBundle().pathForResource("tick", ofType: "wav")
    var soundURL = NSURL.fileURLWithPath(soundPath!)
    self.audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: nil)
    self.audioPlayer.play()
}

现在,如果用户正在运行音乐播放器,我的应用会导致音乐播放器停止。我在文档中读到了关于音频会话默认行为的内容,但我不知道如何应用它。

你能帮忙吗?

谢谢!

2 个答案:

答案 0 :(得分:4)

如果您想知道swift 2的语法,请点击这里:

    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .DuckOthers)
    } catch {
        print("AVAudioSession cannot be set: \(error)")
    }

答案 1 :(得分:3)

根据您希望应用的行为,即应用的音效或音乐应如何与其他应用的背景音频会话互动,您可能需要调整音频会话类别和categoryOption。

如果你只是想播放音效,比如" tick"声音,那么,应分别使用AVAudioSessionCategoryAmbient和DuckOthers,例如:

let audioSession = AVAudioSession.sharedInstance()
var error: NSErrorPointer = nil
audioSession.setCategory(AVAudioSessionCategoryAmbient, withOptions: .DuckOthers, error: error)

但是,我想你实际上是在尝试播放音效,在这种情况下,AudioServices API是一个更合适的选择。您可以在AudioToolbox框架中检查func AudioServicesPlaySystemSound(inSystemSoundID:SystemSoundID)以获取更多详细信息。

另一种常见情况。如果您希望自己的应用专门播放音频,即使其他应用在后台播放音乐,您也需要将类别设置为AVAudioSessionCategorySoloAmbient,例如:

let audioSession = AVAudioSession.sharedInstance()
var error: NSErrorPointer = nil
audioSession.setCategory(AVAudioSessionCategorySoloAmbient, error: error)

我希望你能得到你正在寻找的东西。

相关问题