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      

Hacking with Swift is sponsored by RevenueCat

SPONSORED Take the pain out of configuring and testing your paywalls. RevenueCat's Paywalls allow you to remotely configure your entire paywall view without any code changes or app updates.

Learn more here

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.