Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • AVAudioPlayer implementation in Swift

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 1.12k
    Comment on it

    An easy to implement simple swift class working on AVAudioPlayer depicting various features like play, pause and stop.

     

    1. // creating single instance of class
    2. static let sharedInstance = MyAudioPlayer()
    3. var myAudioPlayer:AVAudioPlayer?
    4. //MARK: Player Key Functions
    5. // checking if playing is running/playing or not
    6. func isRunningAudio()->Bool{
    7. if let audioPlayer = myAudioPlayer{
    8. return audioPlayer.playing
    9. }
    10. return false;
    11. }
    12. // funtion to play audio
    13. func playAudio(audio:String, type:String){
    14. if(myAudioPlayer != nil){
    15. myAudioPlayer?.play()
    16. }
    17. else{
    18. do{
    19. try myAudioPlayer = AVAudioPlayer(contentsOfURL: NSURL(string: NSBundle.mainBundle().pathForResource(audio, ofType: type)!)!)
    20. myAudioPlayer?.delegate = self
    21. myAudioPlayer?.prepareToPlay()
    22. myAudioPlayer?.play()
    23. } catch {
    24. print(error)
    25. }
    26. }
    27. }
    28. // will pause the current playing audio
    29. func pauseAudio(){
    30. myAudioPlayer?.pause()
    31. }
    32. // will stop the player
    33. func stopAudio(){
    34. if let audioPlayer = myAudioPlayer{
    35. audioPlayer.stop()
    36. myAudioPlayer = nil
    37. }
    38. }
    39. //MARK: Player Delegate
    40. // delegate method, will be called when audioplayer is finished playing audio
    41. func audioPlayerDidFinishPlaying(player: AVAudioPlayer, successfully flag: Bool){
    42. if(flag){
    43. myAudioPlayer = nil
    44. }
    45. }
    46.  
    47. // delegate method, will be called when audioplayer encounters any interruption(like call) while playing audio
    48. func audioPlayerBeginInterruption(player: AVAudioPlayer){
    49. myAudioPlayer?.pause()
    50. }
    51. // delegate method, will be called when interruption ends.
    52. func audioPlayerEndInterruption(player: AVAudioPlayer, withOptions flags: Int){
    53. myAudioPlayer?.play()
    54. }

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Reset Password
Fill out the form below and reset your password: