How to play sound using media volume instead of ring volume in ios?

I am trying to play a sound but my current code bases the volume off of the ringtone volume. How to I change this to media volume?

var player: AVAudioPlayer?

...

func playSound(name: String) { 
let url = Bundle.main.url(forResource: name, withExtension: "mp3")!
     do { 
          player = try AVAudioPlayer(contentsOf: url) 
          guard let player = player else {return}
          player.prepareToPlay() 
          player.play() 
     }catch let error { 
          print(error.localizedDescription)
     }
}

...

playSound(name: "baby")

Replies

If there is no active audio session and nothing is playing, the ringer volume is changed (change with buttons is flipped on which most people forget), HUD will say "Ringer". If the app’s audio session is active or actually playing audio we will change its media volume, HUD will say "Volume". The app needs to be in the foreground/active, or playing audio. We recommend apps explicitly use AVAudioSession (see Audio Session Programing Guide) instead of relying on implicit system behavior.