Play Music with AVAudioPlayer iOS Tutorial

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 with Xcode 10 and built for iOS 12.

Open Xcode and create a new Single View App.

For product name, use IOSPlayMusicAVAudioPlayerTutorial and then fill out the Organization Name and Organization Identifier with your customary values. Enter Swift as Language and choose Next.

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 drag them from the Finder window to the Project folder. 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: 56, Width: 343, Height:17

  • Middle Label -> X: 137, Y: 119, Width: 101, Height: 36

  • Left Button -> X: 16, Y: 220, Width: 119, Height: 102

  • Right Button -> X:258, Y: 220, Width: 101, 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.png

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:Timer!

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 Timer 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"
    let path = Bundle.main.path(forResource: "Future Islands - Tin Man", ofType: "mp3")!
    let url = URL(fileURLWithPath: path)
    do {
        audioPlayer =  try AVAudioPlayer(contentsOf: url)
    } catch {
        // can't load file

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: Any) {
    if isPlaying {
        isPlaying = false
    } else {
        isPlaying = true
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #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 Timer object, which will call the updateTime method every second. Let's implement this method.

@objc func updateTime() {
    let currentTime = Int(audioPlayer.currentTime)
    let minutes = currentTime/60
    let seconds = currentTime - minutes * 60
    playedTime.text = String(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 on a real device, press the play/pause and stop button to control the music.

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