Search code examples
iosswiftswift3avaudioplayer

Swift 3.0 AVAudioPlayer Playing audio over music


Currently this is the code I'm using to play my sound during the button press.

var player: AVAudioPlayer?

    let url = Bundle.main.url(forResource: "Sound/yatch", withExtension: "mp3")!

    do {
        player = try AVAudioPlayer(contentsOf: url)
        guard let player = player else { return }

        player.prepareToPlay()
        player.play()
    } catch let error {
        print(error.localizedDescription)
    }

Im trying to get this audio to run over whats currently playing (etc Spotify, pandora, Music). How would I go about doing this?


Solution

  • Set the audio session of your application to play over the currently playing audio:

    try? AVAudioSession.sharedInstance().setActive(true)
    try? AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
    

    According to the AVAudioSession headers, AVAudioSessionCategoryAmbient will play audio with music, etc.

    /*  Use this category for background sounds such as rain, car engine noise, etc.
     Mixes with other music. */
    public let AVAudioSessionCategoryAmbient: String