如何在不停止播放音乐的情况下播放 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 or .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 函数。你也可以阅读更多关于mixWithOthers,但重点是:

An option that indicates whether audio from this session mixes with audio from active sessions in other audio apps.