Build Simple Audio Player App in Swift

October 18, 2017

In this tutorial I am going to create simple audio player to play list of songs in iOS devices. Songs are added to resource files
Following user interface controllers are used to build this App


Your finished App will be like this

Now we will see how we are going to build the above App step by step using Swift language

(1) Create Single View Application and Add Songs

First create the single view application in XCODE and then drag and drop the song folder into Project Navigator

(2) Add UITableVew  to ViewController

Now I want to show these songs in the UITableVew.
Select Main.storyboard file and click on the View Controller. Now you can drag and drop the UITableView from the Object Library into the View Controller

To work with UITableView you need two protocol UITableViewDelegate, UITableViewDataSource so you need to implement these two protocol under ViewController class.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

      override func viewDidLoad() {
        // Do any additional setup after loading the view, typically from a nib.

overridefunc didReceiveMemoryWarning() {
        // Dispose of any resources that can be recreated.

(3) Create Outlet for UITableView
Now you can create IBOutlet for the UITableView

 @IBOutlet weak var tableView: UITableView!

(4) Loading songs to array
In this step you can define the array and load the songs to array

Add the following code to to your ViewController class

var songs: [String] = []

To get the songs from the resource folder I am going to write a function getSongs() which will return the array of songs

 func getSongs() -> [String] {
        var names: [String] = []
        let path = Bundle.main.resourceURL?.appendingPathComponent("songs")
            let songs =   try FileManager.default.contentsOfDirectory(at: path!, includingPropertiesForKeys: nil, options: FileManager.DirectoryEnumerationOptions.skipsHiddenFiles)
            for song in songs{
                let strArray =  song.absoluteString.components(separatedBy: "/")
                var songName = strArray[strArray.count-1].replacingOccurrences(of: "%20", with: " ")
                songName =  songName.replacingOccurrences(of: ".mp3", with: "")
        return names

So this is our getSong() function to get list of the songs. You call this function inside the viewDidLoad() function

songs =  getSongs()

(5) Show the songs in UITableView
Now you have the songs loaded to your array and you want to display them in the UITableView. You need following two methods to display songs in the UITableView

   func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.songs.count
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: "cell")!
        cell.textLabel?.text = self.songs[indexPath.row]
        return cell

Next thing you have to do is, add the following code to viewDidLoad() function

self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.delegate = self
        tableView.dataSource = self

Now you can run the application and you should get following screen in your simulator

(6) Play the song when you touch the row in UITableView
Now you can start code to play the song when you touch the row in the UITableView

First import the AVFoundation library
import AVFoundation
Then create the varibale for the audio player
var player = AVAudioPlayer()

Then I am going to create playSong(index: Int). This function will take one argument which is the index of the row of the UITableView. Based on the integer value I can get the name of the song from the array and then I can look for the path of the song from the resource bundle

func playSong(index: Int){
            let songPath = Bundle.main.path(forResource: songs[index], ofType: ".mp3", inDirectory: "songs")
            try player =  AVAudioPlayer(contentsOf: URL(fileURLWithPath: songPath!))

Now you need to call above method when user touch the row. So we have following method for it

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        playSong(index: indexPath.row)