iOS Developer Library

Developer

AVFoundation Framework Reference AVAudioPlayer Class Reference

Options
Deployment Target:

On This Page
Language:

AVAudioPlayer

An instance of the AVAudioPlayer class, called an audio player, provides playback of audio data from a file or memory.

Apple recommends that you use this class for audio playback unless you are playing audio captured from a network stream or require very low I/O latency. For an overview of audio technologies, see Audio & Video Starting Point and Using Audio in Multimedia Programming Guide.

Using an audio player you can:

  • Play sounds of any duration

  • Play sounds from files or memory buffers

  • Loop sounds

  • Play multiple sounds simultaneously, one sound per audio player, with precise synchronization

  • Control relative playback level, stereo positioning, and playback rate for each sound you are playing

  • Seek to a particular point in a sound file, which supports such application features as fast forward and rewind

  • Obtain data you can use for playback-level metering

The AVAudioPlayer class lets you play sound in any audio format available in iOS and OS X. You implement a delegate to handle interruptions (such as an incoming phone call on iOS) and to update the user interface when a sound has finished playing. The delegate methods are described in AVAudioPlayerDelegate Protocol Reference.

To play, pause, or stop an audio player, call one of its playback control methods, described in Configuring and Controlling Playback.

This class uses the Objective-C declared properties feature 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.

To configure an appropriate audio session for playback on iOS, refer to AVAudioSession Class Reference and AVAudioSessionDelegate Protocol Reference. To learn how your choice of file formats impacts the simultaneous playback of multiple sounds, refer to iOS Hardware and Software Audio Codecs in Multimedia Programming Guide.

Inheritance


Conforms To


Import Statement


Swift

import AVFoundation

Objective-C

@import AVFoundation;

Availability


Available in iOS 2.2 and later.
  • Plays a sound asynchronously.

    Declaration

    Swift

    func play() -> Bool

    Objective-C

    - (BOOL)play

    Return Value

    Returns YEStrue on success, or NOfalse on failure.

    Discussion

    Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Plays a sound asynchronously, starting at a specified point in the audio output device’s timeline.

    Declaration

    Swift

    func playAtTime(_ time: NSTimeInterval) -> Bool

    Objective-C

    - (BOOL)playAtTime:(NSTimeInterval)time

    Parameters

    time

    The number of seconds to delay playback, relative to the audio output device’s current time. For example, to start playback three seconds into the future from the time you call this method, use code like this:

    • NSTimeInterval playbackDelay = 3.0; // must be ≥ 0
    • [myAudioPlayer playAtTime: myAudioPlayer.deviceCurrentTime + playbackDelay];

    Return Value

    YEStrue on success, or NOfalse on failure.

    Discussion

    Use this method to precisely synchronize the playback of two or more AVAudioPlayer objects. This code snippet shows the recommended way to do this:

    • // Before calling this method, instantiate two AVAudioPlayer objects and
    • // assign each of them a sound.
    • - (void) startSynchronizedPlayback {
    • NSTimeInterval shortStartDelay = 0.01; // seconds
    • NSTimeInterval now = player.deviceCurrentTime;
    • [player playAtTime: now + shortStartDelay];
    • [secondPlayer playAtTime: now + shortStartDelay];
    • // Here, update state and user interface for each player, as appropriate
    • }

    To learn about the virtual audio output device’s timeline, read the description for the deviceCurrentTime property.

    Calling this method implicitly calls the prepareToPlay method if the audio player is not already prepared to play.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.

  • Pauses playback; sound remains ready to resume playback from where it left off.

    Declaration

    Swift

    func pause()

    Objective-C

    - (void)pause

    Discussion

    Calling pause leaves the audio player prepared to play; it does not release the audio hardware that was acquired upon calling play or prepareToPlay.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Stops playback and undoes the setup needed for playback.

    Declaration

    Swift

    func stop()

    Objective-C

    - (void)stop

    Discussion

    Calling this method, or allowing a sound to finish playing, undoes the setup performed upon calling the play or prepareToPlay methods.

    The stop method does not reset the value of the currentTime property to 0. In other words, if you call stop during playback and then call play, playback resumes at the point where it left off.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Prepares the audio player for playback by preloading its buffers.

    Declaration

    Swift

    func prepareToPlay() -> Bool

    Objective-C

    - (BOOL)prepareToPlay

    Return Value

    Returns YEStrue on success, or NOfalse on failure.

    Discussion

    Calling this method preloads buffers and acquires the audio hardware needed for playback, which minimizes the lag between calling the play method and the start of sound output.

    Calling the stop method, or allowing a sound to finish playing, undoes this setup.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • playing playing Property

    A Boolean value that indicates whether the audio player is playing (YEStrue) or not (NOfalse). (read-only)

    Declaration

    Swift

    var playing: Bool { get }

    Objective-C

    @property(readonly, getter=isPlaying) BOOL playing

    Discussion

    To find out when playback has stopped implement the audioPlayerDidFinishPlaying:successfully: delegate method.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • volume volume Property

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

    Declaration

    Swift

    var volume: Float

    Objective-C

    @property float volume

    Discussion

    A value of 0.0 indicates silence; a value of 1.0 (the default) indicates full volume for the audio player instance.

    Use this property to control an audio player’s volume relative to other audio output.

    To provide UI in iOS for adjusting system audio playback volume, use the MPVolumeView class, which provides media playback controls that users expect and whose appearance you can customize.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • pan pan Property

    The audio player’s stereo pan position.

    Declaration

    Swift

    var pan: Float

    Objective-C

    @property float pan

    Discussion

    By setting this property you can position a sound in the stereo field. A value of –1.0 is full left, 0.0 is center, and 1.0 is full right.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.

  • rate rate Property

    The audio player’s playback rate.

    Declaration

    Swift

    var rate: Float

    Objective-C

    @property float rate

    Discussion

    This property’s default value of 1.0 provides normal playback rate. The available range is from 0.5 for half-speed playback through 2.0 for double-speed playback.

    To set an audio player’s playback rate, you must first enable rate adjustment as described in the enableRate property description.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    var enableRate: Bool

    Objective-C

    @property BOOL enableRate

    Discussion

    To enable adjustable playback rate for an audio player, set this property to YEStrue after you initialize the player and before you call the prepareToPlay instance method for the player.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 5.0 and later.

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

    Declaration

    Swift

    var numberOfLoops: Int

    Objective-C

    @property NSInteger numberOfLoops

    Discussion

    A value of 0, which is the default, means to play the sound once. Set a positive integer value to specify the number of times to return to the start and play again. For example, specifying a value of 1 results in a total of two plays of the sound. Set any negative integer value to loop the sound indefinitely until you call the stop method.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • delegate delegate Property

    The delegate object for the audio player.

    Declaration

    Swift

    unowned(unsafe) var delegate: AVAudioPlayerDelegate!

    Objective-C

    @property(assign) id< AVAudioPlayerDelegate > delegate

    Discussion

    The object that you assign to be an audio player’s delegate becomes the target of the notifications described in AVAudioPlayerDelegate Protocol Reference. These notifications let you respond to decoding errors, audio interruptions (such as an incoming phone call), and playback completion.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • settings settings Property

    The audio player’s settings dictionary, containing information about the sound associated with the player. (read-only)

    Declaration

    Swift

    var settings: [NSObject : AnyObject]! { get }

    Objective-C

    @property(readonly) NSDictionary *settings

    Discussion

    An audio player’s settings dictionary contains keys for the following information about the player’s associated sound:

    The settings keys are described in AV Foundation Audio Settings Constants.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.

  • The number of audio channels in the sound associated with the audio player. (read-only)

    Declaration

    Swift

    var numberOfChannels: Int { get }

    Objective-C

    @property(readonly) NSUInteger numberOfChannels

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • An array of AVAudioSessionChannelDescription objects associated with the audio player

    Declaration

    Swift

    var channelAssignments: [AnyObject]!

    Objective-C

    @property(nonatomic, copy) NSArray *channelAssignments

    Discussion

    The default value for this property is nil. When non-nil, this array must have the same number of elements as returned by the numberOfChannels property. You can use this property to help you assign output to play to different channels.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 7.0 and later.

  • duration duration Property

    Returns the total duration, in seconds, of the sound associated with the audio player. (read-only)

    Declaration

    Swift

    var duration: NSTimeInterval { get }

    Objective-C

    @property(readonly) NSTimeInterval duration

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

    See Also

    currentTime

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

    Declaration

    Swift

    var currentTime: NSTimeInterval

    Objective-C

    @property NSTimeInterval currentTime

    Discussion

    If the sound is playing, currentTime is the offset of the current playback position, measured in seconds from the start of the sound. If the sound is not playing, currentTime is the offset of where playing starts upon calling the play method, measured in seconds from the start of the sound.

    By setting this property you can seek to a specific point in a sound file or implement audio fast-forward and rewind functions.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • The time value, in seconds, of the audio output device. (read-only)

    Declaration

    Swift

    var deviceCurrentTime: NSTimeInterval { get }

    Objective-C

    @property(readonly) NSTimeInterval deviceCurrentTime

    Discussion

    The value of this property increases monotonically while an audio player is playing or paused.

    If more than one audio player is connected to the audio output device, device time continues incrementing as long as at least one of the players is playing or paused.

    If the audio output device has no connected audio players that are either playing or paused, device time reverts to 0.

    Use this property to indicate “now” when calling the playAtTime: instance method. By configuring multiple audio players to play at a specified offset from deviceCurrentTime, you can perform precise synchronization—as described in the discussion for that method.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 4.0 and later.

  • url url Property

    The URL for the sound associated with the audio player. (read-only)

    Declaration

    Swift

    var url: NSURL! { get }

    Objective-C

    @property(readonly) NSURL *url

    Discussion

    Returns nil if the audio player was not initialized with a URL.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

    See Also

    data

  • data data Property

    The data object containing the sound associated with the audio player. (read-only)

    Declaration

    Swift

    var data: NSData! { get }

    Objective-C

    @property(readonly) NSData *data

    Discussion

    Returns nil if the audio player has no data (that is, if it was not initialized with an NSData object).

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

    See Also

    url

  • A Boolean value that specifies the audio-level metering on/off state for the audio player.

    Declaration

    Swift

    var meteringEnabled: Bool

    Objective-C

    @property(getter=isMeteringEnabled) BOOL meteringEnabled

    Discussion

    The default value for the meteringEnabled property is off (Boolean NOfalse). Before using metering for an audio player, you need to enable it by setting this property to YEStrue. If player is an audio player instance variable of your controller class, you enable metering as shown here:

    • [self.player setMeteringEnabled: YES];

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Returns the average power for a given channel, in decibels, for the sound being played.

    Declaration

    Swift

    func averagePowerForChannel(_ channelNumber: Int) -> Float

    Objective-C

    - (float)averagePowerForChannel:(NSUInteger)channelNumber

    Parameters

    channelNumber

    The audio channel whose average power value you want to obtain. Channel numbers are zero-indexed. A monaural signal, or the left channel of a stereo signal, has channel number 0.

    Return Value

    A floating-point representation, in decibels, of a given audio channel’s current average power. A return value of 0 dB indicates full scale, or maximum power; a return value of –160 dB indicates minimum power (that is, near silence).

    If the signal provided to the audio player exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).

    Discussion

    To obtain a current average power value, you must call the updateMeters method before calling this method.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Returns the peak power for a given channel, in decibels, for the sound being played.

    Declaration

    Swift

    func peakPowerForChannel(_ channelNumber: Int) -> Float

    Objective-C

    - (float)peakPowerForChannel:(NSUInteger)channelNumber

    Parameters

    channelNumber

    The audio channel whose peak power value you want to obtain. Channel numbers are zero-indexed. A monaural signal, or the left channel of a stereo signal, has channel number 0.

    Return Value

    A floating-point representation, in decibels, of a given audio channel’s current peak power. A return value of 0 dB indicates full scale, or maximum power; a return value of –160 dB indicates minimum power (that is, near silence).

    If the signal provided to the audio player exceeds ±full scale, then the return value may exceed 0 (that is, it may enter the positive range).

    Discussion

    To obtain a current peak power value, you must call the updateMeters method before calling this method.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

  • Refreshes the average and peak power values for all channels of an audio player.

    Declaration

    Swift

    func updateMeters()

    Objective-C

    - (void)updateMeters

    Discussion

    To obtain current audio power values, you must call this method before calling averagePowerForChannel: or peakPowerForChannel:.

    Import Statement

    Objective-C

    @import AVFoundation;

    Swift

    import AVFoundation

    Availability

    Available in iOS 2.2 and later.

    See Also

    meteringEnabled