In order to be able to play audio files inside an iOS app, you first need to add the audio file (e.g. myAudioFile.mp3) to your Xcode project, and then follow the steps below:
- create a path to the audio file
- create an instance of AVAudioPlayer
- play the audio file
Here is how this could translate into code:
Now you could apply various effects on the audio file, such as increasing and decreasing the speed or the pitch. For changing the playback speed you need to first enable the audio player’s rate property. Then inside your calling method you can set the rate to a value between 0.5 (slowest) and 2.0 (fastest). A value of 1.0 would be the normal speed, so you can play the file at any speed from half the normal speed to double the normal speed.
To change the pitch of the audio file, the following steps need to take place in order:
- create an AVAudioEngine object
- create an AVAudioPlayerNode object
- attach AVAudioPlayerNode to AVAudioEngine
- create an AVAudioUnitTimePitch object
- attach AVAudioUnitTimePitch to AVAudioEngine
- connect AVAudioPlayerNode to AVAudioUnitTimePitch
- connect AVAudioUnitTimePitch to an output
- play the audio file
The pitch is measured in cents, a logarithmic value used for measuring musical intervals. One octave equals 1200 cents. One musical semitone is equal to 100 cents. The default value is 1.0 (normal pitch). The range of values is -2400 (lowest pitch) to 2400 (highest pitch). Here is how this could translate into code:
We can also use the iPhone’s microphone to record an audio file that we can play, instead of the sample file we added to our Xcode project. Here is how we could do it:
Now we can replace the hardcoded file (myAudioFile.mp3) with our recording stored in the recordingName variable. Every time the recording is started, this file will be overwritten which is useful to saving space. You can see my demo app (based on Udacity’s course) using all these concepts.
Until next time!