AVAudioSession setCategory Swift 4.2 iOS 12 - Play Sound on Silent
Her der Töne's comment shows you the new syntax, but you also need to activate the audio session after setCategory
:
do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) try AVAudioSession.sharedInstance().setActive(true)} catch { print(error)}
As a workaround, you can call the Objective-C AVAudioSession.setCategory:
method with the NSObject.performSelector:
:
if #available(iOS 10.0, *) { try! AVAudioSession.sharedInstance().setCategory(.playback, mode: .moviePlayback)}else { // Workaround until https://forums.swift.org/t/using-methods-marked-unavailable-in-swift-4-2/14949 isn't fixed AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:error:"), with: AVAudioSession.Category.playback)}
If you want to set the category and options for iOS 9 and earlier then use:
AVAudioSession.sharedInstance().perform(NSSelectorFromString("setCategory:withOptions:error:"), with: AVAudioSession.Category.playback, with: [AVAudioSession.CategoryOptions.duckOthers])
UPDATE:
Issue is fixed in Xcode 10.2.
For Swift 4.2 in iOS 12, it is simply:
try AVAudioSession.sharedInstance().setCategory(.playAndRecord, mode: .default, options: [])