[英]How can I play a sound in swift without stopping the playing music?
I'm using AVAudio to play a sound, but when I do so, the music (In the music app) stops.我正在使用 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")
I want to make the sound act like a notification soud and that the music keeps playing.我想让声音像通知声音一样,并且音乐继续播放。 Any way to do this?
有什么办法可以做到这一点?
Set your AVAudioSession
to .duckOthers
or .mixWithOthers
:将您的
AVAudioSession
设置为.duckOthers
或.mixWithOthers
:
(Before you play sounds): (在播放声音之前):
do {
try AVAudioSession.sharedInstance()
.setCategory(.playback, options: .duckOthers)
try AVAudioSession.sharedInstance()
.setActive(true)
} catch {
print(error)
}
You will first have to define properties of an AVAudioSession
.您首先必须定义
AVAudioSession
的属性。 This lets you chose how to play the sound with the help of setCategory(_:mode:options:)
.这使您可以在
setCategory(_:mode:options:)
的帮助下选择如何播放声音。 What you need is this:你需要的是这样的:
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")
Feel free to experiment with the setCategory
function by passing different configuration options.随意通过传递不同的配置选项来试验
setCategory
function。 You can also read more about mixWithOthers
, but the key point is:您还可以阅读有关
mixWithOthers
的更多信息,但关键是:
An option that indicates whether audio from this session mixes with audio from active sessions in other audio apps.
指示来自此 session 的音频是否与来自其他音频应用程序中活动会话的音频混合的选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.