I saw a lot of tutorials but when i click button (that actvivate The func playsound) The sound doesn’t play. I saw the code reccomended by stackoverflow but nothing. I put
SWIFT 4.2 / XCODE 10.1
Note that you must call
AVAudioSession.sharedInstance().setCategory() with the mode parameter in Swift 4.2.
import AVFoundation
var audioPlayer: AVAudioPlayer?
func playSound() {
if let audioPlayer = audioPlayer, audioPlayer.isPlaying { audioPlayer.stop() }
guard let soundURL = Bundle.main.url(forResource: "audio_file", withExtension: "wav") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback, mode: AVAudioSession.Mode.default)
try AVAudioSession.sharedInstance().setActive(true)
audioPlayer = try AVAudioPlayer(contentsOf: soundURL)
audioPlayer?.play()
} catch let error {
Print.detailed(error.localizedDescription)
}
}