Build Simple Audio Player App in Swift

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.

(3) Create Outlet for UITableView
Now you can create IBOutlet for the 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

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

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

(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

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

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

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

Leave a Reply

Your email address will not be published. Required fields are marked *