Play Music with AVAudioPlayer in iOS8 with Swift

The AVAudioPlayer class provides playback of audio data. In this tuturial a music file will be played, paused and stopped. Furthermore, the track title and playing time will be displayed. This tutorial is made for iOS 8 and Xcode 6.3.1.

Open Xcode and create a new Single View Application. For product name, use IOS8SwiftPlayMusicAVAudioPlayerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and make sure only iPhone is selected in Devices.

For this project we need the images for the play/pause and stop buttons and also the mp3 file. You can download them here. Extract the files and add them to the project. Make sure you copy the items into the destination's folder.

Go to the Storyboard and drag two Labels and two Buttons to the main View. Select each object and fill in the following values in the Size Inspector.

  • Top Label -> X: 16, Y: 60, Width: 568, Height:17
  • Middle Label -> X: 250, Y: 120, Width: 100, Height: 36
  • Left Button -> X: 16, Y: 220, Width: 102, Height: 102
  • Right Button -> X:484,  Y: 220, Width: 102, Height: 102

Again select each object and add the following values in the Attributes Inspector

  • top Label: Center Alignment, Font - System 14.0
  • center Label: Center Alignment. Font - System Bold 30.0
  • left Button: Type -Custom, Image - playpause.png
  • right Button: Type - Custom, Image - stop.p

Press the "Resolve Auto Layout" button from the bottom-right in the Storyboard and select "Reset to Suggested Constraints".

The Storyboard should look like this

Select the Assistant Editor and make sure the ViewController.swift is visible. Ctrl and drag from the top Label and create the following Outlet.

Ctrl and drag from the bottom Label and create the following Outlet.

Ctrl and drag from the play/pause Image and create the following Action.

Ctrl and drag from the stop Image and create the following Action.

Go to the ViewController.swift file and import the AVFoundation framework

import AVFoundation

Add the folowing properties in the ViewController class

var audioPlayer = AVAudioPlayer()
var isPlaying = false
var timer:NSTimer!

The AVAudioPlayer class lets you play sound in any audio format available in iOS. With the isPlaying Boolean we'll determine if the music is currently playing. The NSTimer property is needed for displaying the current time in the music track.

Change the viewDidLoad method in

override func viewDidLoad() {
    trackTitle.text = "Future Islands - Tin Man"
    var path = NSBundle.mainBundle().URLForResource("Future Islands - Tin Man", withExtension: "mp3")
    var error:NSError?
    audioPlayer = AVAudioPlayer(contentsOfURL: path!, error: &error)

The track title is assigned to the track label. Next, the AVAudioplayer is initialized with the music file.Next, implement the playOrPauseMusic method

@IBAction func playOrPauseMusic(sender: AnyObject) {
    if isPlaying {
        isPlaying = false
    } else {
        isPlaying = true
        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: "updateTime", userInfo: nil, repeats: true)

First we check if the track is currently playing. If it is, we pause the track and change the isPlaying property. If the track isn't playing, we play it and change the isPlaying property. Then we'll create a NSTimer object, which will call the updateTime method every second. Let's implement this method.

func updateTime() {
    var currentTime = Int(audioPlayer.currentTime)
    var minutes = currentTime/60
    var seconds = currentTime - minutes * 60
    playedTime.text = NSString(format: "%02d:%02d", minutes,seconds) as String

The currentTime property of audioPlayer will be split up in minutes and seconds, which will be displayed to our playedTime property. Finally implement the stopSound method.

@IBAction func stopMusic(sender: AnyObject) {
    audioPlayer.currentTime = 0
    isPlaying = false


The audioplayer calls the stop method and the currentTime is reset, so the next time when the play button is pressed, it will be played from the start. The isPlaying property is set to false. Build and Run the project, press the play/pause and stop button to control the music.

You can download the source code of the IOS8SwiftPlayMusicAVAudioPlayerTutorial at the ioscreator repository on Github.