我目前正在使用 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.")
}
}
}
最佳答案
将您的 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
ambient
表示声音对此应用程序不重要。默认为 soloAmbient
,这是不可混合的。 (有可能你可以在这里把category设置为ambient
,然后你就可以免费得到mixWithOthers
了。我不经常用那个模式,所以我不记得了默认情况下你得到多少。)如果声音很重要,请参阅模式 .playback
。
通常,您在应用程序中设置一次类别,然后根据需要将 session 设置为事件或非事件。如果我没记错的话,AVAudioPlayer 会自动激活 session ,因此您可能不需要这样做(我通常在低得多的级别工作,并不总是记得高级工具自动执行的操作)。但是,如果您的应用的不同功能有不同的需求,则更改您的类别是合法的。
有关详细信息,请参阅 AVAudioSession.Category和 AVAudioSession .声音播放有很多选项,其中很多都不是很明显(还有一些名字很困惑,我在看你.allowBluetooth
),所以值得阅读文档。
关于ios - 我想在不停止另一个应用程序后台播放音乐的情况下制作音效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66065693/