Most preferably you can use AVFoundation . It provides everything you need to work with audiovisual media.
Update: compatible with Swift 2 , Swift 3, and Swift 4, as suggested by some of you in the comments.
Swift 2.3
import AVFoundation var player: AVAudioPlayer? func playSound() { let url = NSBundle.mainBundle().URLForResource("soundName", withExtension: "mp3")! do { player = try AVAudioPlayer(contentsOfURL: url) guard let player = player else { return } player.prepareToPlay() player.play() } catch let error as NSError { print(error.description) } }
Swift 3
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) let player = try AVAudioPlayer(contentsOf: url) player.play() } catch let error { print(error.localizedDescription) } }
Swift 4 (compatible with iOS 12)
import AVFoundation var player: AVAudioPlayer? func playSound() { guard let url = Bundle.main.url(forResource: "soundName", withExtension: "mp3") else { return } do { try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) try AVAudioSession.sharedInstance().setActive(true) player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue) guard let player = player else { return } player.play() } catch let error { print(error.localizedDescription) } }
Be sure to change the name of your melody, as well as the extension . The file must be correctly imported ( Project Build Phases > Copy Bundle Resources ). You can place it in assets.xcassets for more convenience.
For short audio files, you can use uncompressed audio formats such as .wav because they have the best quality and low impact on the processor. Higher disk space consumption should not matter much for shorter audio files. The longer the files, the better it is to use a compressed format, such as .mp3 , etc. Check out compatible CoreAudio audio formats .
Interesting fact: there are neat little libraries that make playing sounds even easier. :)
For example: SwiftySound
Devapploper Aug 16 '15 at 14:41 2015-08-16 14:41
source share