繁体   English   中英

如何在不停止播放音乐的情况下在 swift 中播放声音?

[英]How can I play a sound in swift without stopping the playing music?

我正在使用 AVAudio 播放声音,但是当我这样做时,音乐(在音乐应用程序中)会停止。

    var audioPlayer: AVAudioPlayer?
    func playSound(sound: String, type: String) {
        if let path = Bundle.main.path(forResource: sound, ofType: type) {
            do {
                audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
                audioPlayer?.play()
            } catch {
                print("ERROR")
            }
        }
    }
    // Some code here
    playSound(sound: "resume", type: "m4a")

我想让声音像通知声音一样,并且音乐继续播放。 有什么办法可以做到这一点?

将您的AVAudioSession设置为.duckOthers.mixWithOthers

(在播放声音之前):

do {
    try AVAudioSession.sharedInstance()
        .setCategory(.playback, options: .duckOthers)
    try AVAudioSession.sharedInstance()
        .setActive(true)
} catch {
    print(error)
}

您首先必须定义AVAudioSession的属性。 这使您可以在setCategory(_:mode:options:)的帮助下选择如何播放声音。 你需要的是这样的:

var audioPlayer: AVAudioPlayer?
func playSound(sound: String, type: String) {
    if let path = Bundle.main.path(forResource: sound, ofType: type) {
        do {
            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers])
            try AVAudioSession.sharedInstance().setActive(true)

            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: path))
            audioPlayer?.play()
        } catch {
            print("ERROR")
        }
    }
}
// Some code here
playSound(sound: "resume", type: "m4a")

随意通过传递不同的配置选项来试验setCategory function。 您还可以阅读有关mixWithOthers的更多信息,但关键是:

指示来自此 session 的音频是否与来自其他音频应用程序中活动会话的音频混合的选项。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM