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

时间:2021-05-01 19:28:40

标签: ios swift iphone uikit

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

Integer a = new Integer(100);
int ax = a.intValue();

我想让声音像通知声音一样,并且音乐继续播放。有什么办法吗?

2 个答案:

答案 0 :(得分:0)

将您的 AVAudioSession 设置为 .duckOthers.mixWithOthers

(播放声音之前):

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

答案 1 :(得分:0)

您首先必须定义 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 的更多信息,但关键在于:

<块引用>

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