AVAudioSession Class Reference

Inherits from
Conforms to
Framework
/System/Library/Frameworks/AVFoundation.framework
Availability
Available in iOS 3.0 and later.
Companion guide
Declared in
AVAudioSession.h
Related sample code

Overview

An instance of the AVAudioSession class, called an audio session, is a singleton object that you employ to set the audio context for your app.

Use this class to:

Configuring the Audio Session

The shared audio session object acts as an intermediary between your app and the system’s media services daemon (and in turn, the underlying audio hardware). The media service is subject to requests from other applications—some of which may be higher priority than your app’s audio needs, such as handling a phone call. Because of this, your app does not directly control certain audio settings; instead, you request preferred values for these settings, and observe properties on the AVAudioSession object (or related port and data source objects) in order to see whether, when, and to what extent your requests take effect.

For example, to set the number of output channels:

  1. Call setPreferredOutputNumberOfChannels:error: with a proposed number of channels.

  2. If that method returns YES, your request was accepted. Otherwise, examine the NSError parameter to find the cause of the error.

  3. Even if your request was accepted, the number of channels you proposed may not be available, or the change might not take effect immediately. Examine the value of the outputNumberOfChannels property to see what the current number of channels is, or use key-value observing to see when it changes.

If an audio route change occurs (due to such events as a phone call or audio use by another app while yours is in the background), you may need to reapply your preferred audio settings. Subscribe to the AVAudioSessionRouteChangeNotification to respond to these events.

Preferred settings may not take effect immediately. For example, you can use the setPreferredDataSource:error: method on the built-in microphone port to select the front microphone while a headset is plugged in—this preference will not take effect until the headset is unplugged and the audio route changes.

Routing and Mixing

Your session’s category helps to determine audio input and output behaviors when multiple sessions are active. Other active sessions may be associated with system services (such as the Music app, turn-by-turn navigation, or a phone call) or background apps that support audio (see “App States and Multitasking”).

To control how your audio session interacts with others, use the setCategory:error: or setCategory:withOptions:error: method. If you choose a category or option that supports mixing (see “Audio Session Categories” and “AVAudioSessionCategoryOptions”), audio from other apps continues when you make your session active.

The system allows only one session to control audio routing. If multiple sessions are active, the system chooses which one controls routing based on priority (system sessions such as a phone call may supersede your app’s session) and whether the session is mixable.

Recording Requires User Permission

Recording audio requires explicit permission from the user. The first time your app’s audio session attempts to use an audio input route while using a category that enables recording (see “Audio Session Categories”), the system automatically prompts the user for permission; alternatively, you can call requestRecordPermission: to prompt the user at a time of your choosing.

After the user grants or denies permission, the system remembers the choice for future use in the same app. If the user has denied your app recoding permission or has not yet responded to the permission prompt, any audio recording sessions record only silence.

Media Services Availability

On iOS, the system provides audio and other multimedia functionality through a shared server process. Under certain circumstances, the system may terminate and restart this process. Your app should be prepared to respond to these events by reinitializing any audio objects (such as players, recorders, converters, or audio queues) in use and reapplying preferred audio session settings.

To respond to a media server restart, subscribe to the AVAudioSessionMediaServicesWereResetNotification.

Tasks

Getting the Shared Audio Session

Requesting User Permission to Record

Managing an Audio Session

Working with Audio Device Settings

Working with Audio Channels

Working with Audio Input and Output Routes

Deprecated Properties and Methods

Properties

availableInputs

An array of input ports available for routing. (read-only)

@property(readonly) NSArray *availableInputs
Discussion

An array of AVAudioSessionPortDescription objects representing audio input devices currently attached to the system and relevant to the audio session’s current category and mode. For example, if the session’s category is AVAudioSessionCategoryPlayAndRecord, the array may contain built-in microphone and (if plugged in) headset microphone ports.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

category

The audio session category. (read-only)

@property(readonly) NSString *category
Discussion

An audio session category (one of the constants listed in “Audio Session Categories”) identifies a set of audio behaviors for your app. The default category is AVAudioSessionCategorySoloAmbient.

Availability
  • Available in iOS 3.0 and later.
Declared In
AVAudioSession.h

categoryOptions

The options associated with the current category. (read-only)

@property(readonly) AVAudioSessionCategoryOptions categoryOptions
Discussion

Use category options to tweak your app’s audio behavior. For a list of options that may be specified in this property, see “AVAudioSessionCategoryOptions”.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

currentRoute

An object describing the current audio input and output route. (read-only)

@property(readonly) AVAudioSessionRouteDescription *currentRoute
Discussion

This object describes the input and output ports associated with the current audio route.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputAvailable

A Boolean value indicating whether an audio input path is available. (read-only)

@property(readonly, getter=isInputAvailable) BOOL inputAvailable
Discussion

YES if an input route is available, or NO otherwise.

Use this property to determine whether the device currently supports audio input.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputDataSource

The currently selected input data source. (read-only)

@property(readonly) AVAudioSessionDataSourceDescription *inputDataSource
Discussion

The value of this property is nil if switching between multiple input sources is not currently possible. This feature is supported only on certain devices and peripherals; for example, on an iPhone equipped with both front- and rear-facing microphones.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputDataSources

An array of available data sources for the audio session’s current input port. (read-only)

@property(readonly) NSArray *inputDataSources
Discussion

An array of AVAudioSessionDataSourceDescription objects representing available input sources, or nil if switching between multiple input sources is not currently possible. This feature is supported only on certain devices and peripherals; for example, on an iPhone equipped with both front- and rear-facing microphones.

You can observe changes to the value of this property using key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputGain

The gain applied to inputs associated with the session. (read-only)

@property(readonly) float inputGain
Discussion

A floating point value ranging from 0.0 to 1.0, where 0.0 represents the lowest gain setting and 1.0 represents the highest gain setting.

You can observe changes to the value of this property using key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputGainSettable

A Boolean value that indicates whether the input gain can be set. (read-only)

@property(readonly, getter=isInputGainSettable) BOOL inputGainSettable
Discussion

Returns YES if the device allows input gain to be changed, or NO otherwise. Not all devices support variable gain, so you should check this property before attempting to set the input gain.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputLatency

The latency for audio input, measured in seconds. (read-only)

@property(readonly) NSTimeInterval inputLatency
Discussion

If the audio session category for your app does not support input recording, this property generates an AVAudioSessionErrorCodeIncompatibleCategory error.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

inputNumberOfChannels

The number of audio input channels for the current route. (read-only)

@property(readonly) NSInteger inputNumberOfChannels
Discussion

You can observe changes to the value of this property using key-value observing. If the audio session category for your app does not support input recording, this property generates an AVAudioSessionErrorCodeIncompatibleCategory error.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

IOBufferDuration

The I/O buffer duration, in seconds, that is currently in effect. (read-only)

@property(readonly) NSTimeInterval IOBufferDuration
Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

maximumInputNumberOfChannels

The largest number of input channels available for the current route. (read-only)

@property(readonly) NSInteger maximumInputNumberOfChannels
Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

maximumOutputNumberOfChannels

The largest number of output channels available for the current route. (read-only)

@property(readonly) NSInteger maximumOutputNumberOfChannels
Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

mode

The audio session mode. (read-only)

@property(readonly) NSString *mode
Discussion

One of the constants listed in “Audio Session Modes,” which together with the audio session’s category indicates to the system how you intend to use audio in your app. You can use a mode to configure the audio system for specific use cases such as video recording, voice or video chat, or taking measurements. The default mode is AVAudioSessionModeDefault.

Availability
  • Available in iOS 5.0 and later.
Declared In
AVAudioSession.h

otherAudioPlaying

A Boolean value indicating whether another app is currently playing audio. (read-only)

@property(readonly, getter=isOtherAudioPlaying) BOOL otherAudioPlaying
Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

outputDataSource

The currently selected output data source. (read-only)

@property(readonly) AVAudioSessionDataSourceDescription *outputDataSource
Discussion

The value of this property is nil if switching between multiple output sources is not currently possible. This feature is supported only on certain USB accessories.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

outputDataSources

An array of available output data sources for the current audio route. (read-only)

@property(readonly) NSArray *outputDataSources
Discussion

An array of AVAudioSessionDataSourceDescription objects representing available output sources, or nil if switching between multiple output sources is not currently possible. This feature is supported only on certain USB accessories.

You can observe changes to the value of this property using key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

outputLatency

The latency for audio output, measured in seconds. (read-only)

@property(readonly) NSTimeInterval outputLatency
Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

outputNumberOfChannels

The number of audio output channels. (read-only)

@property(readonly) NSInteger outputNumberOfChannels
Discussion

You can observe changes to the value of this property using key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

outputVolume

The system-wide output volume set by the user. (read-only)

@property(readonly) float outputVolume
Discussion

A value in the range 0.0 to 1.0, with 0.0 representing the minimum volume and 1.0 representing the maximum volume.

The system-wide output volume may only be set directly by the user; to provide volume control in your app, use the MPVolumeView class.

You can observe changes to the value of this property using key-value observing.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

preferredInput

The preferred input port for audio routing. (read-only)

@property(readonly) AVAudioSessionPortDescription *preferredInput
Discussion

The value of this property indicates the input port selected using the setPreferredInput:error: method. To see the actual current input port, use the currentRoute property. Returns nil if no preference has been set, or if the previously set preferred input is no longer available.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

preferredInputNumberOfChannels

The preferred number of input channels for the current route. (read-only)

@property(readonly) NSInteger preferredInputNumberOfChannels
Discussion

The value of this property indicates the number of channels selected using the setPreferredInputNumberOfChannels:error: method. To see the actual number of channels, use the inputNumberOfChannels property.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

preferredIOBufferDuration

The preferred I/O buffer duration, in seconds. (read-only)

@property(readonly) NSTimeInterval preferredIOBufferDuration
Discussion

The value of this property indicates the buffer duration selected using the setPreferredIOBufferDuration:error: method. To see the actual buffer duration, use the IOBufferDuration property.

Availability
  • Available in iOS 3.0 and later.
Declared In
AVAudioSession.h

preferredOutputNumberOfChannels

The preferred number of output channels for the current route. (read-only)

@property(readonly) NSInteger preferredOutputNumberOfChannels
Discussion

The value of this property indicates number of channels selected using the setPreferredOutputNumberOfChannels:error: method. To see the actual number of channels, use the outputNumberOfChannels property.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

preferredSampleRate

The preferred sample rate, in hertz. (read-only)

@property(readonly) double preferredSampleRate
Discussion

The value of this property indicates the sample rate selected using the setPreferredSampleRate:error: method. To see the actual sample rate, use the sampleRate property.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

sampleRate

The audio sample rate, in hertz, that is currently in effect. (read-only)

@property(readonly) double sampleRate
Availability
  • Available in iOS 6.0 and later.
Related Sample Code
Declared In
AVAudioSession.h

Class Methods

sharedInstance

Returns the singleton audio session.

+ (id)sharedInstance
Availability
  • Available in iOS 3.0 and later.
Declared In
AVAudioSession.h

Instance Methods

overrideOutputAudioPort:error:

Temporarily changes the current audio route.

- (BOOL)overrideOutputAudioPort:(AVAudioSessionPortOverride)portOverride error:(NSError **)outError
Parameters
portOverride

The override option for output. For a list of constants, see “AVAudioSessionPortOverride”.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the new routing option was set successfully, or NO if it was not.

Discussion

Calling this method with the AVAudioSessionPortOverrideSpeaker option and the audio session’s category is AVAudioSessionCategoryPlayAndRecord causes audio to use the built-in speaker and microphone regardless of other settings. This change will only be in effect until the current route changes or you call this method again with the AVAudioSessionPortOverrideNone option.

Apple recommends using the MPVolumeView class to provide user control for audio input and output selection.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

requestRecordPermission:

Request the user’s permission for audio recording.

- (void)requestRecordPermission:(PermissionBlock)response
Parameters
response

A block to be called when recording permission has been granted or denied.

Discussion

Recording audio requires explicit permission from the user. The system automatically prompts the user for permission if you use any session categories that enable recording, or you can call this method to prompt for permission at a time of your choosing. After the user grants or denies permission, the system remembers the choice for future use in the same app. If permission is not granted, or if the user has not yet responded to the permission prompt, any audio recording sessions record only silence.

The response parameter is a block of the PermissionBlock type, whose sole parameter indicates whether the user granted or denied permission to record. This method always returns immediately: if the user has previously granted or denied recording permission, it executes the block when called; otherwise, it displays an alert and executes the block only after the user has responded to the alert.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

setActive:error:

Activates or deactivates your app’s audio session.

- (BOOL)setActive:(BOOL)beActive error:(NSError **)outError
Parameters
beActive

Use YES to activate your app’s audio session or NO to deactivate it.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the session’s active state was changed successfully, or NO if it was not.

Discussion

If another active audio session has higher priority than yours (for example, a phone call), and neither audio session allows mixing, attempting to activate your audio session will fail. Deactivating your session will fail if any associated audio objects (such as queues, converters, players or recorders) are currently running.

Availability
  • Available in iOS 3.0 and later.
Declared In
AVAudioSession.h

setActive:withOptions:error:

Activates or deactivates your app’s audio session using the specified options.

- (BOOL)setActive:(BOOL)active withOptions:(AVAudioSessionSetActiveOptions)options error:(NSError **)outError
Parameters
active

Specify YES to activate your app’s audio session or NO to deactivate it.

options

An integer bit mask containing one or more constants from the “AVAudioSessionSetActiveOptions” enumeration.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the session’s active state was changed successfully, or NO if it was not.

Discussion

If another active audio session has higher priority than yours (for example, a phone call), and neither audio session allows mixing, attempting to activate your audio session will fail. Deactivating your session will fail if any associated audio objects (such as queues, converters, players or recorders) are currently running.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

setCategory:error:

Sets the audio session category.

- (BOOL)setCategory:(NSString *)theCategory error:(NSError **)outError
Parameters
theCategory

The audio session category you want to apply to the audio session. See “Audio Session Categories.”

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the category and options were set successfully, or NO otherwise.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you should set the category and mode before activating the session. You may also set the category or mode while the session is active, but this will result in an immediate route change.

Availability
  • Available in iOS 3.0 and later.
See Also
Declared In
AVAudioSession.h

setCategory:withOptions:error:

Sets the audio session category with the specified options.

- (BOOL)setCategory:(NSString *)category withOptions:(AVAudioSessionCategoryOptions)options error:(NSError **)outError
Parameters
category

The audio session category you want to apply to the audio session. For a list of values, see “Audio Session Categories.”

options

A mask of additional options for handling audio. For a list of constants, see “AVAudioSessionCategoryOptions”

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the category and options were set successfully, or NO otherwise.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you should set the category and mode before activating the session. You may also set the category or mode while the session is active, but this will result in an immediate route change.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

setInputDataSource:error:

Selects a data source for the audio session’s current input port.

- (BOOL)setInputDataSource:(AVAudioSessionDataSourceDescription *)dataSource error:(NSError **)outError
Parameters
dataSource

The data source for the audio session’s input.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the input data source for the audio session was successfully assigned; otherwise NO.

Discussion

You may change the input source only to one of the AVAudioSessionDataSourceDescription objects in the inputDataSources array. Switching between multiple input sources is supported only on certain devices and peripherals; for example, this method can be used to choose between front- and rear-facing microphones on an iPhone equipped with them.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

setInputGain:error:

Changes the input gain to the specified value.

- (BOOL)setInputGain:(float)gain error:(NSError **)outError
Parameters
gain

The new gain value, which must be in the range 0.0 to 1.0, where 0.0 represents the lowest gain setting and 1.0 represents the highest gain setting.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the new gain value was set successfully or NO if it was not.

Discussion

Before calling this method, you should check the value in the inputGainSettable property to make sure the input gain level is settable for the current inputs.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

setMode:error:

Sets the audio session mode.

- (BOOL)setMode:(NSString *)theMode error:(NSError **)outError
Parameters
theMode

The audio session mode you want to apply to the audio session.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

Returns YES on success or NO on failure.

Discussion

The session's category and mode together define how the application intends to use audio. Typically, you should set the category and mode before activating the session. You may also set the category or mode while the session is active, but this will result in an immediate route change.

See “Audio Session Modes” for discussion of modes and their effects.

Availability
  • Available in iOS 5.0 and later.
Declared In
AVAudioSession.h

setOutputDataSource:error:

Sets the output data source for an audio session.

- (BOOL)setOutputDataSource:(AVAudioSessionDataSourceDescription *)dataSource error:(NSError **)outError
Parameters
dataSource

The data source for the audio session’s output.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if the output data source for the audio session was successfully assigned; otherwise, NO.

Discussion

You may change the output source only to one of the AVAudioSessionDataSourceDescription objects in the outputDataSources array. This feature is supported only on certain USB accessories.

Availability
  • Available in iOS 6.0 and later.
Declared In
AVAudioSession.h

setPreferredInput:error:

Sets the preferred input port for audio routing.

- (BOOL)setPreferredInput:(AVAudioSessionPortDescription *)inPort error:(NSError **)outError
Parameters
inPort

An AVAudioSessionPortDescription object describing the port to use for input.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if a request was successfully made, or NO otherwise.

Discussion

Requests a change to the input audio route. To determine whether the change takes effect, use the currentRoute property. (See “Configuring the Audio Session” for details.)

The value of the inPort parameter must be one of the AVAudioSessionPortDescription objects in the availableInputs array. If this parameter specifies a port that is not already part of the current audio route and the app’s session controls audio routing, this method initiates a route change to use the preferred port.

Set a preferred input port only after setting the audio session’s category and mode and activating the session.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

setPreferredInputNumberOfChannels:error:

Sets the preferred number of input channels for the current route.

- (BOOL)setPreferredInputNumberOfChannels:(NSInteger)count error:(NSError **)outError
Parameters
count

The number of input channels you want to use.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if a request was successfully made, or NO otherwise.

Discussion

Requests a change to the number of input channels. To determine whether the change takes effect, use the inputNumberOfChannels property. (See “Configuring the Audio Session” for details.) Requesting a number of input channels less than one or greater than that returned by the maximumInputNumberOfChannels results in an error.

Set a preferred number of input channels only after setting the audio session’s category and mode and activating the session.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

setPreferredIOBufferDuration:error:

Sets the preferred audio I/O buffer duration, in seconds.

- (BOOL)setPreferredIOBufferDuration:(NSTimeInterval)duration error:(NSError **)outError
Parameters
duration

The audio I/O buffer duration, in seconds, that you want to use.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if a request was successfully made, or NO otherwise.

Discussion

Requests a change to the I/O buffer duration. To determine whether the change takes effect, use the IOBufferDuration property. (See “Configuring the Audio Session” for details.)

The audio I/O buffer duration is the number of seconds for a single audio input/output cycle. For example, with an I/O buffer duration of 0.005 s, on each audio I/O cycle:

  • You receive 0.005 s of audio if obtaining input.

  • You must provide 0.005 s of audio if providing output.

The typical maximum I/O buffer duration is 0.93 s (corresponding to 4,096 sample frames at a sample rate of 44.1 kHz). The minimum I/O buffer duration is at least 0.005 s (256 frames), but may be lower depending on the hardware in use.

You can set a preferred I/O buffer duration before or after activating the audio session.

Availability
  • Available in iOS 3.0 and later.
Related Sample Code
Declared In
AVAudioSession.h

setPreferredOutputNumberOfChannels:error:

Sets the preferred number of output channels for the current route.

- (BOOL)setPreferredOutputNumberOfChannels:(NSInteger)count error:(NSError **)outError
Parameters
count

The number of output channels you want to use.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if a request was successfully made, or NO otherwise.

Discussion

Requests a change to the number of output channels. To determine whether the change takes effect, use the outputNumberOfChannels property. (See “Configuring the Audio Session” for details.) Requesting a number of output channels less than one or greater than that returned by the maximumOutputNumberOfChannels results in an error. This feature is only supported on certain devices and peripherals.

Set a preferred number of output channels only after setting the audio session’s category and mode and activating the session.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

setPreferredSampleRate:error:

Sets the preferred sample rate for input and output.

- (BOOL)setPreferredSampleRate:(double)sampleRate error:(NSError **)outError
Parameters
sampleRate

The hardware sample rate you want to use. The available range for hardware sample rate is device dependent. It typically ranges from 8,000 through 48,000 hertz.

outError

On input, a pointer to an error object. If an error occurs, the pointer is set to an NSError object that describes the error. If you do not want error information, pass in nil.

Return Value

YES if a request was successfully made, or NO otherwise.

Discussion

Requests a change to the input and output audio sample rate. To see the effect of this change, use the sampleRate property. (See “Configuring the Audio Session” for details.)

You can set a preferred sample rate before or after activating the audio session.

Availability
  • Available in iOS 6.0 and later.
Related Sample Code
Declared In
AVAudioSession.h

Constants

PermissionBlock

The signature for the block executed when the user responds to a prompt for recording permission.

typedef void (^PermissionBlock)(BOOL granted)
Discussion

The block takes a single parameter:

granted

YES if the user has explicitly granted the app permission for audio recording; NO if the user denied permission.

This block type is used by the requestRecordPermission: method.

Availability
  • Available in iOS 7.0 and later.
Declared In
AVAudioSession.h

Audio Session Categories

Category identifiers for audio sessions, used as values for the setCategory:error: method.

NSString *const AVAudioSessionCategoryAmbient;
NSString *const AVAudioSessionCategorySoloAmbient;
NSString *const AVAudioSessionCategoryPlayback;
NSString *const AVAudioSessionCategoryRecord;
NSString *const AVAudioSessionCategoryPlayAndRecord;
NSString *const AVAudioSessionCategoryAudioProcessing;
NSString *const AVAudioSessionCategoryMultiRoute;
Constants
AVAudioSessionCategoryAmbient

For an app in which sound playback is nonprimary—that is, your app can be used successfully with the sound turned off.

This category is also appropriate for “play along” style apps, such as a virtual piano that a user plays while the Music app is playing. When you use this category, audio from other apps mixes with your audio. Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

Available in iOS 3.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategorySoloAmbient

The default category, used unless you set a category with the setCategory:error: or setCategory:withOptions:error: method.

Your audio is silenced by screen locking and by the Silent switch (called the Ring/Silent switch on iPhone).

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing, use the AVAudioSessionCategoryAmbient category instead.

Available in iOS 3.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryPlayback

For playing recorded music or other sounds that are central to the successful use of your app.

When using this category, your app audio continues with the Silent switch set to silent or when the screen locks. (The switch is called the Ring/Silent switch on iPhone.) To continue playing audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing for this category, use the AVAudioSessionCategoryOptionMixWithOthers option.

Available in iOS 3.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryRecord

For recording audio; this category silences playback audio.

To continue recording audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

The user must grant permission for audio recording (see “Recording Requires User Permission”).

Available in iOS 3.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryPlayAndRecord

For recording (input) and playback (output) of audio, such as for a VoIP (Voice over Internet Protocol) app.

Your audio continues with the Silent switch set to silent and with the screen locked. (The switch is called the Ring/Silent switch on iPhone.) To continue playing audio when your app transitions to the background (for example, when the screen locks), add the audio value to the UIBackgroundModes key in your information property list file.

This category is appropriate for simultaneous recording and playback, and also for apps that record and play back but not simultaneously.

By default, using this category implies that your app’s audio is nonmixable—activating your session will interrupt any other audio sessions which are also nonmixable. To allow mixing for this category, use the AVAudioSessionCategoryOptionMixWithOthers option.

The user must grant permission for audio recording (see “Recording Requires User Permission”).

Available in iOS 3.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryAudioProcessing

For using an audio hardware codec or signal processor while not playing or recording audio. Use this category, for example, when performing offline audio format conversion.

This category disables playback (audio output) and disables recording (audio input).

Audio processing does not normally continue when your app is in the background. However, when your app moves to the background, you can request additional time to complete processing. For more information, see iOS App Programming Guide.

Available in iOS 3.1 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryMultiRoute

For routing distinct streams of audio data to different output devices at the same time. For example, you would use this category to route audio to both a USB device and a set of headphones. Use of this category requires a more detailed knowledge of, and interaction with, the capabilities of the available audio routes.

This category may be used for input, output, or both.

The user must grant permission for audio recording (see “Recording Requires User Permission”).

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

Discussion

Each app running in iOS has a single audio session, which in turn has a single category. You can change your audio session’s category while your app is running.

You can refine the configuration provided by the AVAudioSessionCategoryPlayback, AVAudioSessionCategoryRecord, and AVAudioSessionCategoryPlayAndRecord categories by using an audio session mode, as described in “Audio Session Modes.”

AVAudioSessionCategoryOptions

Constants that specify optional audio behaviors.

typedef enum : NSUInteger {
   AVAudioSessionCategoryOptionMixWithOthers = 1,
   AVAudioSessionCategoryOptionDuckOthers = 2,
   AVAudioSessionCategoryOptionAllowBluetooth = 4,
   AVAudioSessionCategoryOptionDefaultToSpeaker = 8
} AVAudioSessionCategoryOptions;
Constants
AVAudioSessionCategoryOptionMixWithOthers

Mixes audio from this session with audio from other active sessions.

Valid only if the session category is AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryPlayback. (Implicit if the session category is AVAudioSessionCategoryAmbient.)

If you activate your session while using this option, your app’s audio will not interrupt audio from other apps (such as the Music app). If not using this option (or a category that is implicitly mixable), activating your session will interrupt other nonmixable sessions.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryOptionDuckOthers

Causes audio from other sessions to be ducked (reduced in volume) while audio from this session plays.

Valid only if the session category is AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryPlayback.

Use this option if you want audio from your app (for example, voice prompts in a navigation app) to be heard over music or other currently playing audio. Note that ducking begins when you activate your app’s audio session and ends when you deactivate the session.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryOptionAllowBluetooth

Allows Bluetooth handsfree devices to appear as available input routes.

Valid only if the session category is AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryRecord.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionCategoryOptionDefaultToSpeaker

Routes audio from the session to the built-in speaker by default.

Valid only if the session category is AVAudioSessionCategoryPlayAndRecord.

When using this option and no other audio route (such as a headset) is available, session audio will play through the device’s built-in speaker. When not using this option, and no other audio output is available or selected, audio will play through the receiver (a speaker intended to be held to the ear). Note that only iPhone devices are equipped with a receiver; on iPad and iPod touch devices, this option has no effect.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

Audio Session Modes

Mode identifiers for audio sessions, used as values for the setMode:error: method.

NSString *const AVAudioSessionModeDefault;
NSString *const AVAudioSessionModeVoiceChat;
NSString *const AVAudioSessionModeGameChat
NSString *const AVAudioSessionModeVideoRecording;
NSString *const AVAudioSessionModeMeasurement;
NSString *const AVAudioSessionModeMoviePlayback;
NSString *const AVAudioSessionModeVideoChat;
Constants
AVAudioSessionModeDefault

The default mode; used unless you set a mode with the setMode:error: method.

You can use this mode with every audio session category.

Available in iOS 5.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeVoiceChat

Specify this mode if your app is performing two-way voice communication, such as using Voice over Internet Protocol (VoIP).

When this mode is in use, the device’s tonal equalization is optimized for voice and the set of allowable audio routes is reduced to only those appropriate for voice chat. For use with the AVAudioSessionCategoryPlayAndRecord audio session category. Apple recommends using the Voice Processing Audio Unit with this mode (see Audio Unit Hosting Guide for iOS).

Using this mode has the side effect of enabling the AVAudioSessionCategoryOptionAllowBluetooth category option.

Available in iOS 5.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeGameChat

Do not set this mode directly. This mode is set by Game Kit on behalf of an application that uses a GKVoiceChat object. This mode is valid only with the AVAudioSessionCategoryPlayAndRecord category.

If you need similar behavior and are not using a GKVoiceChat object, use AVAudioSessionModeVoiceChat or AVAudioSessionModeVideoChat instead.

Available in iOS 5.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeVideoRecording

Specify this mode if your app is recording a movie.

For use with the AVAudioSessionCategoryRecord audio session category. Also works with the AVAudioSessionCategoryPlayAndRecord category. On devices with more than one built-in microphone, the microphone closest to the video camera is used.

Using this mode may result in the system providing appropriate audio signal processing.

If your app records video, you can use the AVCaptureSession class to control your audio session instead of setting this mode directly.

Available in iOS 5.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeMeasurement

Specify this mode if your app is performing measurement of audio input or output.

When this mode is in use, the device does minimal signal processing on input and output audio. For use with the AVAudioSessionCategoryPlayback, AVAudioSessionCategoryRecord, or AVAudioSessionCategoryPlayAndRecord audio session categories. If recording on devices with more than one built-in microphone, the primary microphone is used.

Available in iOS 5.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeMoviePlayback

Specify this mode if your app is playing back movie content.

When this mode is in use, signal processing is employed to enhance movie playback for certain audio routes such as built-in speaker or headphones.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionModeVideoChat

Specify this mode if your app is engaging in online video conferencing.

When this mode is in use, the device’s tonal equalization is optimized for voice and the set of allowable audio routes is reduced to only those appropriate for video chat. For use with the AVAudioSessionCategoryPlayAndRecord or AVAudioSessionCategoryRecord audio session category. Apple recommends using the Voice Processing Audio Unit with this mode (see Audio Unit Hosting Guide for iOS).

Using this mode has the side effect of enabling the AVAudioSessionCategoryOptionAllowBluetooth category option.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

Discussion

Each app running in iOS has a single audio session, which in turn has a single mode. A mode refines the device’s audio configuration according to the purpose of the mode. Change your audio session’s mode only if your audio session category is configured to disallow mixing with other apps (see AVAudioSessionCategoryOptionMixWithOthers); mode applies to the system as a whole, so an app whose session is active and nonmixable will typically typically control the mode for the system.

AVAudioSessionInterruptionOptions

A constant that indicates the state of the audio session following an interruption.

typedef enum : NSUInteger {
   AVAudioSessionInterruptionOptionShouldResume = 1
} AVAudioSessionInterruptionOptions;
Constants
AVAudioSessionInterruptionOptionShouldResume

Interruption by another audio session has ended and the app may resume its audio session.

This value may be present for the AVAudioSessionInterruptionOptionKey key in the userInfo dictionary of the AVAudioSessionInterruptionNotification notification if the interruption type is AVAudioSessionInterruptionTypeEnded. It serves as a hint that it is appropriate for your app to resume audio playback without waiting for user input. Apps that do not normally require user input to begin audio playback (such as games) may ignore this flag and always resume playback upon ending an interruption.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionSetActiveOptions

A flag that provides additional information about your app’s audio intentions upon session activation or deactivation.

typedef enum : NSUInteger {
   AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation = 1
} AVAudioSessionSetActiveOptions;
Constants
AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation

When passed in the flags parameter of the setActive:withOptions:error: instance method, indicates that when your audio session deactivates, other audio sessions that had been interrupted by your session can return to their active state.

This flag is used only when deactivating your audio session; that is, when you pass a value of NO in the beActive parameter of the setActive:withOptions:error: instance method.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionPortOverride

Constants for use with the overrideOutputAudioPort:error: method.

typedef enum : NSUInteger {
   AVAudioSessionPortOverrideNone    = 0,
   AVAudioSessionPortOverrideSpeaker = 'spkr'
} AVAudioSessionPortOverride;
Constants
AVAudioSessionPortOverrideNone

Do not override the output audio port. Use this option to route audio to the system default outputs for the current category and mode.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionPortOverrideSpeaker

Override the current inputs and outputs and route audio to the built-in speaker and microphone. Only valid with the AVAudioSessionCategoryPlayAndRecord category.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReason

Constants indicating the reason for an audio route change.

typedef enum : NSUInteger {
   AVAudioSessionRouteChangeReasonUnknown = 0,
   AVAudioSessionRouteChangeReasonNewDeviceAvailable = 1,
   AVAudioSessionRouteChangeReasonOldDeviceUnavailable = 2,
   AVAudioSessionRouteChangeReasonCategoryChange = 3,
   AVAudioSessionRouteChangeReasonOverride = 4,
   AVAudioSessionRouteChangeReasonWakeFromSleep = 6,
   AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory = 7,
   AVAudioSessionRouteChangeReasonRouteConfigurationChange = 8,
} AVAudioSessionRouteChangeReason;
Constants
AVAudioSessionRouteChangeReasonUnknown

The reason for the change is unknown.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonNewDeviceAvailable

A user action (such as plugging in a headset) has made a preferred audio route available.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonOldDeviceUnavailable

The previous audio output path is no longer available.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonCategoryChange

The category of the session object changed. Also used when the session is first activated.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonOverride

The output route was overridden by the app.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonWakeFromSleep

The route changed when the device woke up from sleep.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonNoSuitableRouteForCategory

The route changed because no suitable route is now available for the specified category.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonRouteConfigurationChange

The set of input and output ports has not changed, but their configuration has—for example, a port’s selected data source has changed.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

Discussion

These constants appear as possible values for the AVAudioSessionRouteChangeReasonKey key in the userInfo dictionary in a AVAudioSessionRouteChangeNotification notification.

AVAudioSessionInterruptionType

Constants that describe the state of the audio interruption.

typedef enum : NSUInteger {
   AVAudioSessionInterruptionTypeBegan = 1,
   AVAudioSessionInterruptionTypeEnded = 0,
} AVAudioSessionInterruptionType;
Constants
AVAudioSessionInterruptionTypeBegan

The system interrupted the audio session.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionInterruptionTypeEnded

The interruption ended.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

Notification User Info Keys

Keys available in the user info dictionary of an interruption notification.

NSString *const AVAudioSessionInterruptionTypeKey;
NSString *const AVAudioSessionInterruptionOptionKey;
   
NSString *const AVAudioSessionRouteChangeReasonKey;
NSString *const AVAudioSessionRouteChangePreviousRouteKey;
Constants
AVAudioSessionInterruptionTypeKey

An NSNumber object containing an unsigned integer that identifies the type of interruption. For a list of possible values, see “AVAudioSessionInterruptionType”.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionInterruptionOptionKey

An NSNumber object containing an unsigned integer that identifies any options associated with the interruption. For a list of possible flags, see “AVAudioSessionInterruptionOptions”.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangeReasonKey

An NSNumber object containing an unsigned integer that identifies the reason why the route changed. For a list of possible values, see “AVAudioSessionRouteChangeReason”.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionRouteChangePreviousRouteKey

An AVAudioSessionRouteDescription object describing audio route settings from before the route change.

Available in iOS 6.0 and later.

Declared in AVAudioSession.h.

Interruption Flags

Constants that indicate the state of the audio session following an interruption. (Deprecated. Use the constants in “AVAudioSessionInterruptionOptions” instead.)

enum {
   AVAudioSessionInterruptionFlags_ShouldResume = 1
};
Constants
AVAudioSessionInterruptionFlags_ShouldResume

Indicates that your audio session is active and immediately ready to be used. Your app can resume the audio operation that was interrupted. (Deprecated. Use AVAudioSessionInterruptionOptionShouldResume instead.)

Look for this flag in the flags parameter when your audio session delegate’s endInterruptionWithFlags: method is invoked.

Available in iOS 4.0 and later.

Declared in AVAudioSession.h.

Activation Flags

Flags that provide additional information about your app’s audio intentions upon session activation or deactivation. (Deprecated. Use the constants in “AVAudioSessionSetActiveOptions” instead.)

enum {
   AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation = 1
};
Constants
AVAudioSessionSetActiveFlags_NotifyOthersOnDeactivation

When passed in the flags parameter of the setActive:withFlags:error: instance method, indicates that when your audio session deactivates, other audio sessions that had been interrupted by your session can return to their active state. (Deprecated. Use AVAudioSessionSetActiveOptionNotifyOthersOnDeactivation instead.)

This flag is used only when deactivating your audio session; that is, when you pass a value of NO in the beActive parameter of the setActive:withFlags:error: instance method.

Available in iOS 4.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCode

Error codes used in NSError objects returned by AVAudioSession methods.

typedef enum : NSInteger {
   AVAudioSessionErrorCodeNone                   =  0,
   AVAudioSessionErrorCodeMediaServicesFailed    = 'msrv',
   AVAudioSessionErrorCodeIsBusy                 = '!act',
   AVAudioSessionErrorCodeIncompatibleCategory   = '!cat',
   AVAudioSessionErrorCodeCannotInterruptOthers  = '!int',
   AVAudioSessionErrorCodeMissingEntitlement     = 'ent?',
   AVAudioSessionErrorCodeSiriIsRecording        = 'siri',
   AVAudioSessionErrorCodeCannotStartPlaying     = '!pla',
   AVAudioSessionErrorCodeBadParam               = -50,
   AVAudioSessionErrorCodeUnspecified            = 'what'
} AVAudioSessionErrorCode;
Constants
AVAudioSessionErrorCodeNone

The operation succeeded.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeMediaServicesFailed

An attempt was made to use the audio session during or after a Media Services failure.

See “Media Services Availability” for more information.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeIsBusy

An attempt was made to set its audio session inactive, but it is still actively playing and/or recording.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeIncompatibleCategory

An attempt was made to perform an operation not permitted in its current category.

For example, this error type can occur if you call setPreferredInputNumberOfChannels:error: while the session’s category is set to AVAudioSessionCategoryPlayback.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeCannotInterruptOthers

An attempt was made to make a nonmixable audio session active while the app was in the background.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeMissingEntitlement

An attempt was made to perform an operation for which the app does not have the required entitlements.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeSiriIsRecording

An attempt was made to perform an operation that is not allowed while Siri is recording.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeCannotStartPlaying

An attempt was made to start audio playback, but playback is not allowed.

This error type can occur if the app’s Information property list does not permit audio use, or if the app is in the background and using a category which does not allow background audio.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeBadParam

An attempt was made to set a property to an illegal value.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

AVAudioSessionErrorCodeUnspecified

No further error information is available. This error type typically results when the audio system is in an inconsistent state.

Available in iOS 7.0 and later.

Declared in AVAudioSession.h.

Notifications

AVAudioSessionInterruptionNotification

Posted on the main thread when an audio interruption occurs.

The userInfo dictionary of this notification contains the AVAudioSessionInterruptionTypeKey. If the interruption type is AVAudioSessionInterruptionTypeBegan, the app’s audio session has been interrupted and is no longer active. If the interruption type is AVAudioSessionInterruptionTypeEnded, this dictionary also contains the AVAudioSessionInterruptionOptionKey key.

Availability
Declared In
AVAudioSession.h

AVAudioSessionRouteChangeNotification

Posted on the main thread when the system’s audio route changes.

The userInfo dictionary of this notification contains the AVAudioSessionRouteChangeReasonKey and AVAudioSessionRouteChangePreviousRouteKey keys, which provide information about the route change.

Availability
Declared In
AVAudioSession.h

AVAudioSessionMediaServicesWereLostNotification

Posted on the main thread when the media server terminates.

Use this notification as a cue to take any appropriate steps to handle requests that come in before the server restarts. Most applications need not subscribe to this notification and should subscribe to the AVAudioSessionMediaServicesWereResetNotification notification instead.

This notification has no userInfo dictionary.

Availability
Declared In
AVAudioSession.h

AVAudioSessionMediaServicesWereResetNotification

Posted on the main thread when the media server restarts.

Subscribe to this notification to ensure that your app recovers as intended if the media server restarts. See “Media Services Availability” for details.

This notification has no userInfo dictionary.

Availability
Declared In
AVAudioSession.h