NEW: Start my new Ultimate Portfolio App course with a free Hacking with Swift+ trial! >>

how to set AVAudio session correctly

Forums > Swift

I have background music playing but when other sounds are activated it stops. I am sure it is to do with AVAudiosession. I have tried a few different settings but nothing seems to work.

I have a function button to start and stop the background music. The code for both is below.

class MusicPlayer {
static let shared = MusicPlayer()

func startBackgroundMusic() {
if let bundle = Bundle.main.path(forResource: "playlistbj", ofType: "mp3") {
  let backgroundMusic = NSURL(fileURLWithPath: bundle)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: backgroundMusic as URL)
        guard let audioPlayer = audioPlayer else {return}
        audioPlayer.numberOfLoops = -1
        audioPlayer.prepareToPlay()
        audioPlayer.play()
    } catch {
        print(error)
    }}

do{
    if #available(iOS 10.0, *) {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default, options: [.mixWithOthers])
    } else {
        // Fallback on earlier versions
    }
    print("Playback ok")
    try AVAudioSession.sharedInstance().setActive(true)
    print("session is active")

    guard let player = audioPlayer else{
        return
    }

    player.play()
}
catch {
    print ("oops")
}
}

   

Hacking with Swift is sponsored by Essential Developer

SPONSORED From January 26th to 31st you can join a FREE crash course for iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a senior developer!

Save your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.