In this tutorial we are going to learn how to play a music MP3 file stored on a remote server or in the cloud like Amazon Spider web Services. In fact the MP3 file I am going to employ in this tutorial is stored in Amazon Deject in a S3 bucket.

This tutorial will contain both a video demonstration and a detailed description.

Outset comes the video:

To brainstorm with let's create a new project with a unmarried ViewController.

Then let's observe a UIButton in our Objects Library and elevate and drop it on our initial ViewController like and so:

Play button

To make our UIButton to look similar a Play button permit's elevate and driblet some icons to our project:

Play MP3 example in Swift- Icons screen shot

Now, select UIButton and set the "player_control_play_50px.png" as UIButton Epitome. And then clear the UIButton title because nosotros no longer need it. Your UIButton should now look similar this:

PlayButton+PlayIconScreenShot

Next step is very important. We demand to create an Outlet for UIButton, and so that nosotros tin interact with it.

  1. Open your ViewController in Banana Editor
  2. Select the UIButton, then agree "control" push on your keyboard, click and drag and drop the blueish connector line right beneath the Class declaration.
  3. Give your Outlet a name "playButton". Similar so:

ButtonOutlet

Let'southward go back to our ViewController and let's import the only framework we will need to employ to make our little app be able to play music. Then, in your ViewController add a new line at the very top:

To play MP3 music file located on remote server we will need to access it with URL. In your viewDidLoad let's create a URL object.

override func viewDidLoad() {         super.viewDidLoad()   // Do whatever boosted setup after loading the view, typically from a nib.                
allow url = NSURL(string: "https://s3.amazonaws.com/kargopolov/kukushka.mp3")  }                

We will now need to create a AVPlayerItem and AVPlayer. And because we will need to access these two objects from other functions let's declare them every bit properties of our ViewController. Outside of viewDidLoad() function, right under the ViewController course opening curly bracket  "{" add these ii lines:

                  var playerItem:AVPlayerItem?     var player:AVPlayer?                

Now permit's create a new AVPlayerLayer and add it to our main View. Your viewDidLoad() office will now expect like this:

                  override func viewDidLoad() {         super.viewDidLoad()         // Practise any boosted setup after loading the view, typically from a nib.                  permit url = NSURL(string: "https://s3.amazonaws.com/kargopolov/BlueCafe.mp3")         playerItem = AVPlayerItem(URL: url!)         thespian=AVPlayer(playerItem: playerItem!)         allow playerLayer=AVPlayerLayer(actor: player!)         playerLayer.frame=CGRectMake(0, 0, 300, 50)         cocky.view.layer.addSublayer(playerLayer)     }                

To brand our button handle tap events let'due south add together to our viewDidLoad function the post-obit line of code:

                  playButton.addTarget(self, action: "playButtonTapped:", forControlEvents: .TouchUpInside)                

this will instruct the button to call "playButtonTapped:" action when user taps on it. So allow'southward create playButtonTapped: action.

                  func playButtonTapped(sender: AnyObject) {        }                

When user taps on Play button we need to make a decision. If music is currently not playing, we need to start playing it. Else, if music is currently playing, then nosotros need to suspension it. Now our playButtonTapped function will look like this:

                  func playButtonTapped(sender: AnyObject) {         if player?.rate == 0         {             player!.play()             playButton.setImage(UIImage(named: "player_control_pause_50px.png"), forState: UIControlState.Normal)         } else {             role player!.pause()             playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)         }     }                

If we need to handle state of affairs when our music item finished playing, nosotros can add together an observer listening for AVPlayerItemDidPlayToEndTimeNotification. So let's create a new part called viewWillAppear and add together a needed observer. Our viewWillAppear function will wait like this:

                  override func viewWillAppear(animated: Bool) {         NSNotificationCenter.defaultCenter().addObserver(self, selector: "finishedPlaying:", proper name: AVPlayerItemDidPlayToEndTimeNotification, object: playerItem)     }                

This will make application call finishedPlaying: part when music item played all the way to the cease.

And the reason we added an observer in viewWillAppear part is because when our view disappears nosotros need to remove this observer. To do that let's create another function called viewWillDisappear and use information technology to remove observer from NSNotificationCenter.

                  override func viewWillDisappear(animated: Bool) {         NSNotificationCenter.defaultCenter().removeObserver(self)     }                

Now allow's implement finishedPlaying: function and when information technology is chosen, nosotros will:

  1. Reset UIButton image
  2. Rewind our music file all the way to its initial position, and so that user tin can tap on the button once more and play the file from the beginning.
                  func finishedPlaying(myNotification:NSNotification) {         playButton.setImage(UIImage(named: "player_control_play_50px.png"), forState: UIControlState.Normal)                  let stopedPlayerItem: AVPlayerItem = myNotification.object every bit! AVPlayerItem         stopedPlayerItem.seekToTime(kCMTimeZero)     }                

Done!

Nosotros can now play our music file! 🙂

Also, I accept i more swift lawmaking example to help you make music playback slider update and smoothly slide every bit music is playing on. Check out how to Add Periodic TimeObserver to Update Music Playback Slider to your AVPlayer.

Happy learning!