Skip to content

Instantly share code, notes, and snippets.

@genedelisa
Last active January 20, 2017 10:16
Show Gist options
  • Save genedelisa/3c43c18eb1ff19dc8598 to your computer and use it in GitHub Desktop.
Save genedelisa/3c43c18eb1ff19dc8598 to your computer and use it in GitHub Desktop.
Swift AVAudioPlayer
class Sound : NSObject {
/// The player.
var avPlayer:AVAudioPlayer!
/**
Uses AvAudioPlayer to play a sound file.
The player instance needs to be an instance variable. Otherwise it will disappear before playing.
*/
func readFileIntoAVPlayer() {
var error: NSError?
let fileURL:NSURL = NSBundle.mainBundle().URLForResource("Sumer Is Icumen In", withExtension: "caf")
// the player must be a field. Otherwise it will be released before playing starts.
self.avPlayer = AVAudioPlayer(contentsOfURL: fileURL, error: &error)
if avPlayer == nil {
if let e = error {
println(e.localizedDescription)
}
}
println("playing \(fileURL)")
avPlayer.delegate = self
avPlayer.prepareToPlay()
avPlayer.volume = 1.0
avPlayer.play()
}
func stopAVPLayer() {
if avPlayer.playing {
avPlayer.stop()
}
}
func toggleAVPlayer() {
if avPlayer.playing {
avPlayer.pause()
} else {
avPlayer.play()
}
}
}
// MARK: AVAudioPlayerDelegate
extension Sound : AVAudioPlayerDelegate {
func audioPlayerDidFinishPlaying(player: AVAudioPlayer!, successfully flag: Bool) {
println("finished playing \(flag)")
}
func audioPlayerDecodeErrorDidOccur(player: AVAudioPlayer!, error: NSError!) {
println("\(error.localizedDescription)")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment