Skip to content

Instantly share code, notes, and snippets.

@alansvits
Created January 14, 2018 06:57
Show Gist options
  • Save alansvits/037d9a810c07baa24bf15d0d17cc59cc to your computer and use it in GitHub Desktop.
Save alansvits/037d9a810c07baa24bf15d0d17cc59cc to your computer and use it in GitHub Desktop.
import AVFoundation
var audioPlayer: AVAudioPlayer!
let soundURL = Bundle.main.url(forResource: "soundName", withExtension: "soundFormat")
do {
audioPlayer = try AVAudioPlayer(contentsOf: soundURL!)
} catch {
print(error)
}
audioPlayer.play()
import AVFoundation
var player: AVAudioPlayer?
func playSound() {
guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
try AVAudioSession.sharedInstance().setActive(true)
/* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
/* iOS 10 and earlier require the following line:
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */
guard let player = player else { return }
player.play()
} catch let error {
print(error.localizedDescription)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment