I'm having an issue trying to use the
AVAudioSessionCategorySoloAmbient
category on the audio session.My intent is to play a sound when my ViewController first opens. But only if the ringer is on
However, the sound plays regardless of whether the ringer is on or off.
I don't have access to a device so I'm only testing on the simulator.
This is a completely fresh project, everything being what XCode automatically generates, with only the following file altered
The ViewController is as follows
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer: AVAudioPlayer?
override func viewDidLoad() {
super.viewDidLoad()
do {
try self.playSound(file: "startup", ext: "wav")
} catch {
print("Something went wrong")
}
}
func playSound(file: String, ext: String) throws {
let path = Bundle.main.path(forResource: file, ofType: ext)!
let url = URL(fileURLWithPath: path)
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategorySoloAmbient)
try session.setActive(true)
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
self.audioPlayer?.prepareToPlay()
self.audioPlayer?.play()
}
}
As I understand it, what I want should be the default behaviour anyway. So I have also tried omitting the following lines. But the same thing happens.
let session = AVAudioSession.sharedInstance()
try session.setCategory(AVAudioSessionCategorySoloAmbient)
try session.setActive(true)
I'm using Swift 4.1
Any help appreciated!