![](/img/trans.png)
[英]I want to make sound effects without stopping the music playing in the background in another app
[英]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.