UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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

2      

Reading the Apple documentation, as I am looking to add some sound to the apps I am developing, I saw these articles in the docuementation.

Configuration for Audio playback on iOS and tvOS

In addition to setting up the AVPlayer, it is necessary to enable the playback in Background mode (the setting in Xcode).

Configuring ambient

Using the .ambient configuration allows the mixing of audio channels.

   try audioSession.setCategory(.ambient)

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

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.