Created
January 14, 2018 06:57
-
-
Save alansvits/037d9a810c07baa24bf15d0d17cc59cc to your computer and use it in GitHub Desktop.
Playing sound in swift 4. Source: https://stackoverflow.com/questions/32036146/how-to-play-a-sound-using-swift/32036291#32036291
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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