AVAudioPlayer – How to work it.

In this blog we will learn about how to work with audio files in iOS(swift).

Framework:

A framework is a bundle that contains a dynamic shared library along with associated resources, such as nib files, image files, and header files. When you develop an application, your project links to one or more frameworks.
For example;
iPhone application projects link by default to the Foundation, UIKit, and Core Graphics frameworks.

AVFoundation:(iOS FrameWork)
AV Foundation framework provides essential services for working with time-based audiovisual media on iOS. By using this, you can easily play, capture, edit or encode media files.

About Audio:
• To play sound files, you can use AVAudioPlayer.
• To record audio, you can use AVAudioRecorder.

AVAudioPlayer:

The AVAudioPlayer class lets you play sound in any audio format available in iOS. The properties of this class used for managing information about a sound such as the playback point within the sound’s timeline, and for accessing playback options such as volume and looping.This class is available from iOS 2.2.
AVAudioPlayer class provides playback of audio data from a file or memory.

AVAudioPlayer Initialization Methods

1. – initWithContentsOfURL:error:
Initializes and returns an audio player for playing a designated sound file.

Parameters:

url : A url identifying the sound file to play.
error: If an error occurs, upon return the NSError object describes the error.

2. – initWithData:error:

Initializes and returns an audio player for playing a designated memory buffer.

Parameters:

data: A block of data containing a sound to play.
error: If an error occurs, upon return the NSError object describes the error.


3. – initWithContentsOfURL:fileTypeHint:error:

Initializes and returns an audio player using the specified URL and file type hint.

Parameters:

url : A url identifying the sound file to play.
utiString: A UTI that is used as a file type hint.
error: If an error occurs, upon return the NSError object describes the error.


4. – initWithData:fileTypeHint:error:

Initialises and returns an audio player using the specified data and file type hint.

Parameters:

data: A block of data containing a sound to play.
utiString: A UTI that is used as a file type hint.
error: If an error occurs, upon return the NSError object describes the error.

AVAudioPlayer Methods:


- play
Plays a sound asynchronously.
Returns YES if the audio played successfully.

– pause
Pauses playback, sound remains ready to resume playback from where it left off.


- stop
Stops playback and undoes the setup needed for playback.


- prepareToPlay
Prepares the audio player for playback by preloading its buffers.

– playAtTime:(time)
Plays a sound asynchronously, starting at a specified point in the audio output device’s timeline.

Parameters:
time: The number of seconds to delay playback, relative to the audio output device’s current time.
Returns YES if the audio played successfully.

Properties of AVAudioPlayer

Playing
Returns a boolean value that indicates whether the audio player is playing (YES) or not (NO).

Volume
The playback volume for the audio player, ranging from 0.0 through 1.0 on a linear scale.

Pan
The audio player’s stereo pan position.

Rate
The audio player’s playback rate.

EnableRate
A Boolean value that specifies whether playback rate adjustment is enabled for an audio player.

NumberOfLoops
The number of times a sound will return to the beginning, upon reaching the end, to repeat playback.

Delegate
The delegate object for the audio player.

Settings
The audio player’s settings dictionary, containing information about the sound associated with the player.

NumberOfChannels
The number of audio channels in the sound associated with the audio player.

ChannelAssignments
An array of AVAudioSessionChannelDescription objects associated with the audio player

Duration
Returns the total duration, in seconds, of the sound associated with the audio player.

CurrentTime
The playback point, in seconds, within the timeline of the sound associated with the audio player.

DeviceCurrentTime
The time value, in seconds, of the audio output device.

URL
The URL for the sound associated with the audio player.

Data
The data object containing the sound associated with the audio player.

Supported audio formats

AAC (MPEG-4 Advanced Audio Coding)
ALAC (Apple Lossless)
AMR (Adaptive Multi-rate)
HE-AAC (MPEG-4 High Efficiency AAC)
iLBC (internet Low Bit Rate Codec)
Linear PCM (uncompressed, linear pulse code modulation)
MP3 (MPEG-1 audio layer 3)
µ-law and a-law

Advantages

AVAudioPlayer can play songs when app is in background.
AVAudioPlayer can handle files of any duration unlike System Sound Services that has a 30 second limit.
The source for Audio data and AVAudioPlayer can either be files or in-memory sources.
AVAudioPlayer can be set to loop a certain number of times or infinitely.
AVAudioPlayer can also handle playing multiple sounds from multiple sources simultaneously.

Disadvantages

AVAudioPlayer has some timing ability, it’s not precise.
AVAudioPlayer has a limited ability to alter the data stream.
AVAudioPlayer cannot play songs from a playlist.

Sample code in swift

First you need to import AVFoundation
Then create instance for it for example,
let player: AVAudioPlayer = AVAudioPlayer()
Then you can load the url in the instance of the AVAudioPlayer like

let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String) // Instead of file you need to use your file name(audio file name).

let url = NSURL.fileURLWithPath(path!)
do {
try self.player = AVAudioPlayer(contentsOfURL: url)
} catch { //To handle if error occurred
print(“Player not available”)
}

To play the audio

@IBAction func playButtonPressed(sender: AnyObject) {
self.player.play()
}

To pause the audio

@IBAction func pauseButtonPressed(sender: AnyObject) {
self.player.pause()
}

To stop the audio

@IBAction func stopButtonPressed(sender: AnyObject) {
self.player.stop()
}

I hope you have learnt from this blog on how to work with audio files such as to play, stop and access the information about the audio file in the supported format.

Mohanapriya,
iOS Developer,
Mallow Technologies.

Leave a Reply

%d bloggers like this: