I guess I could use AVAudioPlayer to play a sound, however, what I need is to just play a short sound and I don\'t need any loops or fine-grained control over t
The other answers here use Objective-C so I am providing a Swift version here. Swift uses Automatic Reference Counting (ARC), so I am not aware of any memory leak issues with this answer (as warned about in the accepted answer).
You can use the AudioToolbox framework to play short sounds when you do not need much control over how they are played.
Here is how you would set it up:
import UIKit
import AudioToolbox
class PlaySoundViewController: UIViewController {
var soundURL: NSURL?
var soundID: SystemSoundID = 0
@IBAction func playSoundButtonTapped(sender: AnyObject) {
let filePath = NSBundle.mainBundle().pathForResource("yourAudioFileName", ofType: "mp3")
soundURL = NSURL(fileURLWithPath: filePath!)
if let url = soundURL {
AudioServicesCreateSystemSoundID(url, &soundID)
AudioServicesPlaySystemSound(soundID)
}
}
}
Notes:
yourAudioFileName.mp3 (or .wav, etc) to your project.import AudioToolboxBy importing the AVFoundation framework, you can use AVAudioPlayer. It works for both short audio clips and long songs. You also have more control over the playback than you did with the AudioToolbox method.
Here is how you would set it up:
import UIKit
import AVFoundation
class PlaySoundViewController: UIViewController {
var mySound: AVAudioPlayer?
// a button that plays a sound
@IBAction func playSoundButtonTapped(sender: AnyObject) {
mySound?.play() // ignored if nil
}
override func viewDidLoad() {
super.viewDidLoad()
// initialize the sound
if let sound = self.setupAudioPlayerWithFile("yourAudioFileName", type: "mp3") {
self.mySound = sound
}
}
func setupAudioPlayerWithFile(file: NSString, type: NSString) -> AVAudioPlayer? {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer: AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("Player not available")
}
return audioPlayer
}
}
Notes:
import AVFoundtation and to add yourAudioFileName.mp3 to your project.