我想在不停止另一个应用程序后台播放的音乐的情况下制作音效

tou*_*you 3 iphone uikit ios swiftui

我目前正在使用 SwiftUI 开发一个应用程序。有一个功能,当你点击它时会播放声音效果。当我在实际设备上测试时,后台播放的 Spotify 音乐停止了。是否可以使用AVFoundation在不停止音乐的情况下播放音效?另外,如果有更好的方法来实现这一点,请帮助我。

import Foundation
import AVFoundation

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:Could not find and play the sound file.")
        }
       
    }
}
Run Code Online (Sandbox Code Playgroud)

Rob*_*ier 5

将您的 AVAudioSession 类别选项设置为.mixWithOthers

let audioSession = AVAudioSession.sharedInstance()
do {
    try audioSession.setCategory(.ambient, mode: .default, options: [.mixWithOthers])
} catch {
    print("Failed to set audio session category.")
}

audioSession.setActive(true) // When you're ready to play something
Run Code Online (Sandbox Code Playgroud)

ambient表明声音对此应用并不重要。默认值为soloAmbient,不可混合。(你可以将类别设置到ambient这里,然后你就可以免费获得mixWithOthers。我不经常使用该模式,所以我不记得默认情况下你会获得多少。)如果声音很重要,请查看模式.playback

通常,您在应用程序中设置一次类别,然后根据需要将会话设置为活动或非活动。如果我没记错的话,AVAudioPlayer 将自动激活会话,因此您可能不需要这样做(我通常在较低级别上工作,并且并不总是记得高级工具自动执行的操作)。但是,如果应用程序的不同功能有不同的需求,则更改类别是合法的。

有关更多详细信息,请参阅AVAudioSession.CategoryAVAudioSession。声音播放中有很多选项,其中许多选项并不明显(其中一些选项的名称非常令人困惑,我正在看着你.allowBluetooth),因此值得通读文档。