Advertisement
Guest User

SoundPlayer Singleton

a guest
Mar 1st, 2015
207
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import AVFoundation
  2.  
  3. class SoundPlayer {
  4.  
  5.     // Singleton in order to access the player from 'everywhere'
  6.     class var sharedInstance : SoundPlayer {
  7.         struct Static {
  8.             static let instance : SoundPlayer = SoundPlayer()
  9.         }
  10.         return Static.instance
  11.     }
  12.    
  13.     // Properties
  14.     var error:NSError?
  15.     var audioPlayer = AVAudioPlayer()
  16.     let soundURL = NSURL(string:"/System/Library/Audio/UISounds/sms-received1.caf")
  17.    
  18.     init() {
  19.         AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient, error: nil)
  20.         AVAudioSession.sharedInstance().setActive(true, error: nil)
  21.        
  22.         audioPlayer = AVAudioPlayer(contentsOfURL: soundURL, error: &error)
  23.        
  24.         if (error != nil) {
  25.             println("[SoundPlayer] There was an error: \(error)")
  26.         }
  27. //        else {
  28. //            audioPlayer.prepareToPlay()
  29. //        }
  30.     }
  31.    
  32.     func playSound() {
  33.         if (audioPlayer.playing) {
  34.             audioPlayer.stop()
  35.         }
  36.         audioPlayer.play()
  37.     }
  38. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement