Using AVAudioPlayer to play sounds in iOS applications
In iOS applications, there are scenarios where we need to play media sounds (like mp3) in iOS applications. In this tutorial, we will discuss how to play sound files added to XCode using AVAudioPlayer in the iOS app.
The AVAudioPlayer object is used to play audio data from a file or buffer. The AVAudioPlayer plays data from a file or buffer. It is declared as follows.
We can use the AVAudioPlayer to play audio of any duration from a file or buffer. We can also control the volume, rate, panning, and looping behavior of the played audio. It plays multiple sounds simultaneously by synchronizing the playback of multiple players.
The AVAudioPlayer provides the following methods to control the playback behavior.
Let's create a project which plays the sound file added to the project.
First, we need to add the AVFoundation framework to our project. For this purpose, go to the General tab in XCode project properties and tap the "+" icon in the framework and libraries section given at the bottom. We will get the dialogue box to choose from the frameworks. Type AVFoundation in the box as shown below to add the framework.
For this project, we will add a sample mp3 or wav sound file. Once we have the sound file, add it to our project by dragging and dropping it into XCode, as shown below.
In the ViewController class, we need to import the AVFoundation framework to use the framework classes.
Now, let's create the AVAudioPlayer class object in the ViewController class.
As we have created AVAudioPlayer() object now, we need to read the sound file we have just added to the XCode. For this purpose, add the following code in ViewController.
If we notice that we have used Bundle in the above code to find the Sound file named as Sound of type mp3.
Now, we will play sound using the play () method of AVAudioPlayer, as shown below.
Let's add the play button in the Main.storyboard by clicking which, we can play the sound in our iOS app.
Now create the action outlet of the play button in the ViewController and add the following code.
Now, we will notice once we run the app on an iOS device and tap on the play button, the audio will be played.
The AVAudioPlayer class provides several other properties to control the playback of the audio player. Let's look at the properties of the AVAudioPlayer class.