Swift 3.0 AVAudioPlayer Playing audio over music

This is currently the code that I use to play sound at the click of a button.

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)
    }

I am trying to get this sound to work on what is currently playing (etc. Spotify, pandora, Music). How can i do this?

+4
source share
1 answer

Set the sound session of the application to play the currently playing sound:

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

According to the headings AVAudioSession, it AVAudioSessionCategoryAmbientwill play sound with music, etc.

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

Source: https://habr.com/ru/post/1664751/


All Articles