Home » How - To / Tutorial » Programming » Creating an Audio Player with Swift

Creating an Audio Player with Swift

You will learn how to create an audio player with Swift, comprising of a play button, stop button, and a slider for volume adjustment. We will begin by adding an audio file to the resources of the project. If you do this, any audio format will be supported.

Identify an audio file, and drag and drop it in the Supporting files folder of your project. I have put an mp3 audio called test.mp3 and I have put it in the audiofiles folder of my project, so do the same.

Creating the User Interface

We want to add the two buttons and the slider. Just select the Main.storyboard and display the Object Library by View -> Utilities -> Show Object Library. Add the components on the view window by dragging them from the Library. Modify them to look as follows:

iOS-Swift-Audio-Player Creating an Audio Player with Swift

Select the scene view with the storyboard canvas. Get the list of menu options by selecting the Auto Layout Resolve Auto Layout Issues menu. Select reset. From the view canvas, select slider. Drag the slider just below the class declaration in the Assistant Editor. Create an outlet connection and call it vControl in the dialog that will appear. Drag the play button to below the viewDidLoad(). Establish an action method named pAudio on the Touch Up inside.

Do the same for the stop button and call the action sAudio. Drag the slider object to the Assistant Editor panel beneath the created actions. From the dialog, establish a connection method called adVolume.

Select the ViewController.swift file after closing the Assistant Editor panel, and add the following to it:

Action Methods

Implement the following methods in the ViewController.swift file:

Creation and Initialization of AVAudioPlayer Object

Add the following code in the viewDidLoad() method of the ViewController.swift file:

Implementation of the AVAudioPlayerDelegate Protocol Methods

To do this, add the following protocols to the ViewController.swift file:

You can now run your app and play around with the two buttons and the slider.

One thought on “Creating an Audio Player with Swift

  1. Johann says:

    could you please share a link to download the project?

Leave a Reply

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

Name *
Email *

This site uses Akismet to reduce spam. Learn how your comment data is processed.