简体   繁体   中英

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.

    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 :

(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 . This lets you chose how to play the sound with the help of 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. You can also read more about mixWithOthers , but the key point is:

An option that indicates whether audio from this session mixes with audio from active sessions in other audio apps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM