### start() Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/start%28%29 Starts the sequencer’s player. If prepareToPlay() has not been called, the framework calls it automatically before starting playback. ```APIDOC ## start() ### Description Starts the sequencer’s player. ### Method Signature ```swift func start() throws ``` ### Discussion If you don’t call `prepareToPlay()`, the framework calls it and then starts the player. ### See Also * `func prepareToPlay()` * `func stop()` ``` -------------------------------- ### prepare() Source: https://developer.apple.com/documentation/avfaudio/avaudioengine/prepare%28%29 Prepares the audio engine for starting. This method preallocates many resources the audio engine requires to start. Use it to responsively start audio input or output. ```APIDOC ## prepare() ### Description Prepares the audio engine for starting. ### Method Signature ```swift func prepare() ``` ### Discussion This method preallocates many resources the audio engine requires to start. Use it to responsively start audio input or output. ``` -------------------------------- ### start() Source: https://developer.apple.com/documentation/avfaudio/avaudioengine/start%28%29 Starts the audio engine. This method calls prepare() if it hasn't been called after stop(). It then initializes the audio hardware via the input and output nodes. An error is thrown if the graph structure is invalid, an AVAudioSession error occurs, or the driver fails to start the hardware. ```APIDOC ## start() ### Description Starts the audio engine. This method calls the `prepare()` method if you don’t call it after invoking `stop()`. It then starts the audio hardware through the `AVAudioInputNode` and `AVAudioOutputNode` instances in the audio engine. ### Throws An error is thrown when: * There’s a problem in the structure of the graph, such as the input can’t route to an output or to a recording tap through converter nodes. * An `AVAudioSession` error occurs. * The driver fails to start the hardware. ### Availability iOS 8.0+ iPadOS 8.0+ Mac Catalyst 13.1+ macOS 10.10+ tvOS 9.0+ visionOS 1.0+ watchOS 2.0+ ```swift func start() throws ``` ``` -------------------------------- ### Start and Play Audio Engine Source: https://developer.apple.com/documentation/avfaudio/avaudioengine This snippet demonstrates how to start the `AVAudioEngine` and begin playback using the `AVAudioPlayerNode`. ```APIDOC ## Start and Play Audio Engine ### Description Before you play the audio, start the engine. ### Code Example ```swift do { try audioEngine.start() playerNode.play() } catch { /* Handle the error. */ } ``` ``` -------------------------------- ### Start Recording with AVAudioRecorder Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/record%28%29 Starts or resumes audio recording. This method implicitly calls prepareToRecord(). ```swift func record() -> Bool ``` -------------------------------- ### Start and Play Audio Engine Source: https://developer.apple.com/documentation/avfaudio/avaudioengine Start the AVAudioEngine and begin playback with the AVAudioPlayerNode. Ensure to handle potential errors during the start process. ```swift do { try audioEngine.start() playerNode.play() } catch { /* Handle the error. */ } ``` -------------------------------- ### Start Audio Engine and Player Source: https://developer.apple.com/documentation/avfaudio/performing-offline-audio-processing Starts the configured `AVAudioEngine` and begins playback on the `AVAudioPlayerNode`. This should be called after enabling manual rendering mode. ```swift do { try engine.start() player.play() } catch { fatalError("Unable to start audio engine: \(error).") } ``` -------------------------------- ### Start AVAudioEngine Source: https://developer.apple.com/documentation/avfaudio/avaudioengine/start%28%29 Call this method to start the audio engine. It may throw an error if there are issues with the audio graph, session, or hardware. ```swift func start() throws ``` -------------------------------- ### Play Audio Asynchronously with AVAudioPlayer Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/play%28%29 Call this method to start audio playback. It implicitly calls prepareToPlay() if the player is unprepared. Returns true if playback starts successfully, otherwise false. ```swift func play() -> Bool ``` -------------------------------- ### Install Audio Tap Example Source: https://developer.apple.com/documentation/avfaudio/avaudionode/installtap%28onbus%3Abuffersize%3Aformat%3Ablock%3A%29 Example of installing an audio tap on an input node to capture audio data. Ensure the engine is started after installation. ```objective-c AVAudioEngine *engine = [[AVAudioEngine alloc] init]; AVAudioInputNode *input = [engine inputNode]; AVAudioFormat *format = [input outputFormatForBus: 0]; [input installTapOnBus: 0 bufferSize: 8192 format: format block: ^(AVAudioPCMBuffer *buf, AVAudioTime *when) { // __'__buf' contains captured audio from the node at time 'when' }]; .... // start engine ``` -------------------------------- ### Get or Set Current Playback Time - Swift Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/currenttime Use this property to get the current playback time in seconds or to seek to a specific time in the audio. If the sound is playing, this value is the offset from the start of the sound. If not playing, it indicates the offset from where playback will start. ```swift var currentTime: TimeInterval { get set } ``` -------------------------------- ### prepareToRecord() Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/preparetorecord%28%29 Creates an audio file and prepares the system for recording. Call this method to start recording as quickly as possible upon calling record(). ```APIDOC ## prepareToRecord() ### Description Creates an audio file and prepares the system for recording. ### Method Signature ```swift func prepareToRecord() -> Bool ``` ### Return Value `true` if successful; otherwise, `false`. ### Discussion Calling this method creates an audio file at the URL you used to create the recorder. If a file already exists at that location, this method overwrites it. Call this method to start recording as quickly as possible upon calling `record()`. ``` -------------------------------- ### Get and Set offsetTime for AVMusicTrack Source: https://developer.apple.com/documentation/avfaudio/avmusictrack/offsettime Use this property to get or set the offset of the track's start time, measured in beats. The default value is 0. ```swift var offsetTime: AVMusicTimeStamp { get set } ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/avfaudio/avaudioengine/init%28%29 Creates an audio engine instance for rendering in real time. ```APIDOC ## init() ### Description Creates an audio engine instance for rendering in real time. ### Method init() ### Return Value A new `AVAudioEngine` instance. ### Discussion To operate in manual rendering mode, which removes real-time running constraints, see `enableManualRenderingMode(_:format:maximumFrameCount:)`. ``` -------------------------------- ### Getting Standard Categories Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/category-swift.struct/audioprocessing Examples of other standard audio session categories available. ```swift static let ambient: AVAudioSession.Category ``` ```swift static let multiRoute: AVAudioSession.Category ``` ```swift static let playAndRecord: AVAudioSession.Category ``` ```swift static let playback: AVAudioSession.Category ``` ```swift static let record: AVAudioSession.Category ``` ```swift static let soloAmbient: AVAudioSession.Category ``` -------------------------------- ### mediaDeviceExtension Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/port/mediadeviceextension Represents an output to a media device vended through a system-wide extension installed by the user. Available on iOS, iPadOS, and Mac Catalyst starting from version 27.0 (Beta). ```APIDOC ## Property ### `static let mediaDeviceExtension: AVAudioSession.Port` #### Description Output to a media device vended through a system-wide extension that the user has installed. #### Availability iOS 27.0+ Beta iPadOS 27.0+ Beta Mac Catalyst 27.0+ Beta ``` -------------------------------- ### Get the number of packets in AVAudioCompressedBuffer Source: https://developer.apple.com/documentation/avfaudio/avaudiocompressedbuffer/packetcount Use this property to retrieve the current number of packets in the buffer. It is available on multiple Apple platforms starting from their respective iOS 9.0 versions. ```swift var packetCount: AVAudioPacketCount { get set } ``` -------------------------------- ### Create an Engine for Audio File Playback Source: https://developer.apple.com/documentation/avfaudio/avaudioengine This snippet demonstrates how to set up an AVAudioEngine to play an audio file. It involves creating an AVAudioFile, an AVAudioEngine, and an AVAudioPlayerNode, then attaching and connecting the player node to the engine's output. ```APIDOC ## Create an Engine for Audio File Playback ### Description To play an audio file, you create an `AVAudioFile` with a file that’s open for reading. Create an audio engine object and an `AVAudioPlayerNode` instance, and then attach the player node to the engine. Next, connect the player node to the audio engine’s output node. The engine performs audio output through an output node, which is a singleton that the engine creates the first time you access it. ### Code Example ```swift let audioFile = /* An AVAudioFile instance that points to file that's open for reading. */ let audioEngine = AVAudioEngine() let playerNode = AVAudioPlayerNode() // Attach the player node to the audio engine. audioEngine.attach(playerNode) // Connect the player node to the output node. audioEngine.connect(playerNode, to: audioEngine.outputNode, format: audioFile.processingFormat) ``` ``` -------------------------------- ### Getting Typed Mutable Channel Data Source: https://developer.apple.com/documentation/avfaudio/avaudiopcmbuffer/mutablechanneldata/float%28_%3A%29 Examples of accessing mutable channel data with different integer types. These are variants of accessing channel data with specific numeric types. ```swift case int16(MutableSpan) ``` ```swift case int32(MutableSpan) ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/avfaudio/avaudioconverterprimeinfo/init%28%29 Creates a priming information instance. ```APIDOC ## init() ### Description Creates a priming information instance. ### Method init() ### Endpoint N/A (SDK method) ### Parameters None ### Request Example ```swift let primeInfo = AVAudioConverterPrimeInfo() ``` ### Response N/A (initialization) ### See Also `init(leadingFrames:leadingFrames:trailingFrames:)` ``` -------------------------------- ### hostTime(forBeats:error:) Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/hosttime%28forbeats%3Aerror%3A%29 Gets the host time the sequence plays at the specified position. This method is valid when the player is in a playing state. It returns 0 with an error, or if the starting position of the player is after the specified beat. The method uses the sequence’s tempo map to translate a beat time from the starting time and the beat of the player. ```APIDOC ## hostTime(forBeats:error:) ### Description Gets the host time the sequence plays at the specified position. ### Method Signature ```swift func hostTime( forBeats inBeats: AVMusicTimeStamp, error outError: NSErrorPointer ) -> UInt64 ``` ### Parameters #### Path Parameters - **inBeats** (AVMusicTimeStamp) - The timestamp for the beat position. - **outError** (NSErrorPointer) - On exit, if an error occurs, a description of the error. ### Discussion This call is valid when the player is in a playing state. It returns `0` with an error, otherwise, or if the starting position of the player is after the specified beat. The method uses the sequence’s tempo map to translate a beat time from the starting time and the beat of the player. ### See Also - `typealias AVMusicTimeStamp` - `func seconds(forBeats: AVMusicTimeStamp) -> TimeInterval` ``` -------------------------------- ### Activate or Deactivate Audio Session Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/setactive%3Aerror%3A Use this method to activate your app's audio session, for example, to start a SharePlay activity. You can also use it to deactivate the session when your app is done with audio. ```Objective-C - (BOOL) setActive:(BOOL) active error:(NSError **) outError; ``` -------------------------------- ### record() Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/record%28%29 Starts or resumes audio recording. This method implicitly calls prepareToRecord(), which creates an audio file and prepares the system for recording. ```APIDOC ## record() ### Description Starts or resumes audio recording. ### Method Signature ```swift func record() -> Bool ``` ### Return Value `true` if successful; otherwise, `false`. ### Discussion Calling this method implicitly calls `prepareToRecord()`, which creates an audio file and prepares the system for recording. ### See Also - `prepareToRecord()` - `record(atTime: TimeInterval)` - `record(forDuration: TimeInterval)` - `record(atTime: TimeInterval, forDuration: TimeInterval)` - `pause()` - `stop()` - `isRecording` - `deleteRecording()` ``` -------------------------------- ### Access Mutable Channel Data as Float Span Source: https://developer.apple.com/documentation/avfaudio/avaudiopcmbuffer/mutablechanneldata/float%28_%3A%29 Use this case to get mutable channel data as a MutableSpan. Available on iOS, iPadOS, macOS, tvOS, visionOS, and watchOS starting from version 27.0. ```swift case float(MutableSpan) ``` -------------------------------- ### Starting a Note Source: https://developer.apple.com/documentation/avfaudio/avaudiounitmidiinstrument Sends a MIDI Note On event to the instrument. ```APIDOC ## func startNote(UInt8, withVelocity: UInt8, onChannel: UInt8) ### Description Sends a MIDI Note On event to the instrument. ### Parameters - **note** (UInt8) - The MIDI note number. - **velocity** (UInt8) - The note velocity. - **channel** (UInt8) - The MIDI channel. ``` -------------------------------- ### Get Beat for Host Time Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/beats%28forhosttime%3Aerror%3A%29 Retrieves the beat position at a specific host time. This method is valid when the player is in a playing state and uses the sequence's tempo map. Returns 0 with an error if the starting position is after the specified host time. ```swift func beats( forHostTime inHostTime: UInt64, error outError: NSErrorPointer ) -> AVMusicTimeStamp ``` -------------------------------- ### init(channel:key:pressure:) Source: https://developer.apple.com/documentation/avfaudio/avmidipolypressureevent/init%28channel%3Akey%3Apressure%3A%29 Creates an event with a channel, MIDI key number, and a key pressure value. ```APIDOC ## init(channel:key:pressure:) ### Description Creates an event with a channel, MIDI key number, and a key pressure value. ### Parameters #### Path Parameters - **channel** (UInt32) - Required - The MIDI channel for the message, between `0` and `15`. - **key** (UInt32) - Required - The MIDI key number to apply the pressure to. - **pressure** (UInt32) - Required - The poly pressure value. ``` -------------------------------- ### init(url:settings:) Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/init%28url%3Asettings%3A%29-5whyq Creates an audio recorder with the specified file URL and audio settings. This initializer can throw an error if the recorder cannot be created. ```APIDOC ## init(url:settings:) ### Description Creates an audio recorder with the specified file system location and audio settings. ### Parameters - **url** (URL) - Required - The file system location to record to. - **settings** ([String : Any]) - Required - The audio settings to use for the recording. ### Return Value A new audio recorder instance, or `nil` if an error occurred. ### Discussion Supported keys for `settings` include `AVFormatIDKey`, `AVSampleRateKey`, and `AVNumberOfChannelsKey`, with specific supported values detailed in the documentation. ``` -------------------------------- ### Get Host Time for Beats Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/hosttime%28forbeats%3Aerror%3A%29 Retrieves the host time corresponding to a specific beat position. This method is valid when the player is in a playing state and uses the sequence's tempo map for conversion. It returns 0 with an error if the starting position is after the specified beat. ```swift func hostTime( forBeats inBeats: AVMusicTimeStamp, error outError: NSErrorPointer ) -> UInt64 ``` -------------------------------- ### Schedule Playback with AVAudioPlayerNode in Objective-C Source: https://developer.apple.com/documentation/avfaudio/avaudioplayernode/play%28at%3A%29 This example demonstrates how to schedule playback to start approximately 0.5 seconds in the future using Objective-C. It calculates the target sample time based on the output format's sample rate and the player's last render time. ```objectivec // Start the engine and player. NSError *nsErr = nil; [_engine startAndReturnError:&nsErr]; if (!nsErr) { const float kStartDelayTime = 0.5; // sec AVAudioFormat *outputFormat = [_player outputFormatForBus:0]; AVAudioFramePosition startSampleTime = _player.lastRenderTime.sampleTime + kStartDelayTime * outputFormat.sampleRate; AVAudioTime *startTime = [AVAudioTime timeWithSampleTime:startSampleTime atRate:outputFormat.sampleRate]; [_player playAtTime:startTime]; } ``` -------------------------------- ### Create and Configure AVAudioEngine Nodes Source: https://developer.apple.com/documentation/avfaudio/performing-offline-audio-processing Sets up an `AVAudioEngine` with a player, reverb, and mixer node. Connects the nodes and schedules the source file for playback. ```swift let engine = AVAudioEngine() let player = AVAudioPlayerNode() let reverb = AVAudioUnitReverb() engine.attach(player) engine.attach(reverb) // Set the desired reverb parameters. reverb.loadFactoryPreset(.mediumHall) reverb.wetDryMix = 50 // Connect the nodes. engine.connect(player, to: reverb, format: format) engine.connect(reverb, to: engine.mainMixerNode, format: format) // Schedule the source file. player.scheduleFile(sourceFile, at: nil) ``` -------------------------------- ### Initialize AVAudioRecorder with Settings Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder Creates an audio recorder instance with specified settings. Ensure the URL is valid and settings conform to expected audio formats. ```swift init(url: URL, settings: [String : Any]) throws ``` -------------------------------- ### beats(forHostTime:error:) Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/beats%28forhosttime%3Aerror%3A%29 Gets the beat the system plays at the specified host time. This call is valid when the player is in a playing state. It returns 0 with an error, otherwise, or if the starting position of the player is after the specified host time. This method uses the sequence’s tempo map to retrieve a beat time from the specified host time. ```APIDOC ## beats(forHostTime:error:) ### Description Gets the beat the system plays at the specified host time. ### Signature ```swift func beats( forHostTime inHostTime: UInt64, error outError: NSErrorPointer ) -> AVMusicTimeStamp ``` ### Parameters #### Path Parameters - **inHostTime** (UInt64) - The host time for the beat position. - **outError** (NSErrorPointer) - On exit, if an error occurs, a description of the error. ### Discussion This call is valid when the player is in a playing state. It returns `0` with an error, otherwise, or if the starting position of the player is after the specified host time. This method uses the sequence’s tempo map to retrieve a beat time from the specified host time. ### See Also - `beats(forSeconds:)` ``` -------------------------------- ### AVBeatRange start Property Declaration Source: https://developer.apple.com/documentation/avfaudio/avbeatrange-c.struct/start This is the declaration of the start property for AVBeatRange. It specifies the starting point of a beat range. ```occ AVMusicTimeStamp start; ``` -------------------------------- ### Prepare to Record Audio Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/preparetorecord%28%29 Call this method to create an audio file and prepare the system for recording. It overwrites existing files at the specified URL and should be invoked before calling record() for optimal performance. ```swift func prepareToRecord() -> Bool ``` -------------------------------- ### start Source: https://developer.apple.com/documentation/avfaudio/avbeatrange-swift.typealias/start The starting beat of the range. This is a read-only property. ```APIDOC ## start ### Description The starting beat of the range. ### Property - `start` (AVMusicTimeStamp) - The starting beat of the range. ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiocompressedbuffer/init%28format%3Apacketcapacity%3Amaximumpacketsize%3A%29 Creates a buffer that contains audio data in a compressed state. ```APIDOC ## init(format:packetCapacity:maximumPacketSize:) ### Description Creates a buffer that contains audio data in a compressed state. ### Parameters - **format** (AVAudioFormat) - The format of the audio the buffer contains. - **packetCapacity** (AVAudioPacketCount) - The capacity of the buffer, in packets. - **maximumPacketSize** (Int) - The maximum size in bytes of a packet in a compressed state. ### Return Value A new `AVAudioCompressedBuffer` instance. ### Discussion You can obtain the maximum packet size from the `maximumOutputPacketSize` property of an `AVAudioConverter` you configure for encoding this format. The method raises an exception if the format is PCM. ### See Also - `init(format: AVAudioFormat, packetCapacity: AVAudioPacketCount)` ``` -------------------------------- ### start Source: https://developer.apple.com/documentation/avfaudio/avbeatrange-c.struct/start The starting beat time stamp of the range. ```APIDOC ## start ### Description The starting beat time stamp of the range. ### Instance Property ```swift AVMusicTimeStamp start; ``` ### Platforms iOS, iPadOS, Mac Catalyst, macOS, tvOS, visionOS, watchOS ``` -------------------------------- ### init() Source: https://developer.apple.com/documentation/avfaudio/avaudio3dvectororientation/init%28%29 Creates a 3D vector orientation instance. ```APIDOC ## init() ### Description Creates a 3D vector orientation instance. ### Method init() ### Parameters None ### Request Example ``` init() ``` ### Response None ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiotime/init%28hosttime%3A%29 Creates an audio time object with the specified host time. ```APIDOC ## init(hostTime:) ### Description Creates an audio time object with the specified host time. ### Parameters #### Path Parameters - **hostTime** (UInt64) - Required - The host time. ### Return Value A new `AVAudioTime` instance. ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiounitmidiinstrument/init%28audiocomponentdescription%3A%29 Creates a MIDI instrument audio unit with the component description you specify. The component type must be `kAudioUnitType_MusicDevice` or `kAudioUnitType_RemoteInstrument`. ```APIDOC ## init(audioComponentDescription:) ### Description Creates a MIDI instrument audio unit with the component description you specify. ### Parameters #### Path Parameters - **description** (AudioComponentDescription) - The description of the audio component. ### Return Value A new `AVAudioUnitMIDIInstrument` instance. ### Discussion The component type must be `kAudioUnitType_MusicDevice` or `kAudioUnitType_RemoteInstrument`. ``` -------------------------------- ### Get Preferred Input Channels Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/preferredinputnumberofchannels Query this property to get the number of channels previously set using `setPreferredInputNumberOfChannels(_:)`. To get the actual number of input channels, use `inputNumberOfChannels`. ```swift var preferredInputNumberOfChannels: Int { get } ``` -------------------------------- ### Prepare Source Audio File and Format Source: https://developer.apple.com/documentation/avfaudio/performing-offline-audio-processing Loads an audio file and retrieves its processing format. Ensure the audio file exists in your bundle. ```swift let sourceFile: AVAudioFile let format: AVAudioFormat do { let sourceFileURL = Bundle.main.url(forResource: "Rhythm", withExtension: "caf")! sourceFile = try AVAudioFile(forReading: sourceFileURL) format = sourceFile.processingFormat } catch { fatalError("Unable to load the source audio file: \(error.localizedDescription).") } ``` -------------------------------- ### init(cmAudioFormatDescription:) Source: https://developer.apple.com/documentation/avfaudio/avaudioformat/init%28cmaudioformatdescription%3A%29-8rdfj Creates an audio format instance from a Core Media audio format description. This initializer is deprecated. ```APIDOC ## init(cmAudioFormatDescription:) ### Description Creates an audio format instance from a Core Media audio format description. ### Method Initializer ### Parameters #### Parameters - **formatDescription** (CMAudioFormatDescription) - The Core Media audio format description. ### Return Value A new `AVAudioFormat` instance, or `nil` if `formatDescription` isn’t valid. ``` -------------------------------- ### AVBeatRange start Property Declaration Source: https://developer.apple.com/documentation/avfaudio/avbeatrange-swift.typealias/start This is the declaration of the 'start' property for AVBeatRange. It indicates the beginning of a beat range. ```swift var start: AVMusicTimeStamp ``` -------------------------------- ### prepareToPlay() Source: https://developer.apple.com/documentation/avfaudio/avaudiosequencer/preparetoplay%28%29 Gets ready to play the sequence by prerolling all events. The framework invokes this method automatically on play if you don’t call it, but it may delay startup. ```APIDOC ## prepareToPlay() ### Description Gets ready to play the sequence by prerolling all events. ### Signature ```swift func prepareToPlay() ``` ### Discussion The framework invokes this method automatically on play if you don’t call it, but it may delay startup. ``` -------------------------------- ### Getting Audio Converter Properties Source: https://developer.apple.com/documentation/avfaudio/avaudioconverter Accesses various properties of the AVAudioConverter to get information about its configuration and capabilities. ```APIDOC ## Properties ### channelMap - **Type**: [NSNumber] - **Description**: An array of integers that indicates which input to derive each output from. ### dither - **Type**: Bool - **Description**: A Boolean value that indicates whether dither is on. ### downmix - **Type**: Bool - **Description**: A Boolean value that indicates whether the framework mixes the channels instead of remapping. ### inputFormat - **Type**: AVAudioFormat - **Description**: The format of the input audio stream. ### outputFormat - **Type**: AVAudioFormat - **Description**: The format of the output audio stream. ### magicCookie - **Type**: Data? - **Description**: An object that contains metadata for encoders and decoders. ### maximumOutputPacketSize - **Type**: Int - **Description**: The maximum size of an output packet, in bytes. ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiochannellayout/init%28layout%3A%29 Creates an audio channel layout object from an existing one. ```APIDOC ## init(layout:) ### Description Creates an audio channel layout object from an existing one. ### Method Signature ```swift init(layout: UnsafePointer) ``` ### Parameters #### Parameters - **layout** (*UnsafePointer*) The existing audio channel layout object. ### Return Value A new `AVAudioChannelLayout` object. ### Discussion If the audio channel layout object’s tag is `kAudioChannelLayoutTag_UseChannelDescriptions`, this initializer attempts to convert it to a more specific tag. ### See Also - `var layout: UnsafePointer` - `convenience init?(layoutTag: AudioChannelLayoutTag)` ``` -------------------------------- ### Initialize AVAudioRecorder Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/init%28url%3Asettings%3A%29-9zay9 Use this initializer to create an instance of AVAudioRecorder. Provide the URL where the audio will be recorded and a dictionary of audio settings. This method can throw an error if initialization fails. ```swift init( URL url: URL, settings: [String : Any] ) throws ``` -------------------------------- ### play(at:) Source: https://developer.apple.com/documentation/avfaudio/avaudioplayernode/play%28at%3A%29 Starts or resumes playback at a specified time. Passing nil starts playback immediately. This method is deprecated. ```APIDOC ## play(at:) ### Description Starts or resumes playback at a time you specify. ### Method `func play(at when: AVAudioTime?) ` ### Parameters #### Path Parameters - **when** (AVAudioTime?) - The node time to start or resume playback. Passing `nil` starts playback immediately. ### Discussion This node is initially in a paused state. The framework enqueues your requests to play buffers or file segments, and any necessary decoding begins immediately. Playback doesn’t begin until the player starts playing through this method. ### Example ```swift // Start the engine and player. NSError *nsErr = nil; [_engine startAndReturnError:&nsErr]; if (!nsErr) { const float kStartDelayTime = 0.5; // sec AVAudioFormat *outputFormat = [_player outputFormatForBus:0]; AVAudioFramePosition startSampleTime = _player.lastRenderTime.sampleTime + kStartDelayTime * outputFormat.sampleRate; AVAudioTime *startTime = [AVAudioTime timeWithSampleTime:startSampleTime atRate:outputFormat.sampleRate]; [_player playAtTime:startTime]; } ``` ``` -------------------------------- ### Initialize AVAudioPlayer Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/init%28contentsofurl%3Afiletypehint%3A%29 Use this initializer to create an audio player instance. Provide the URL of the audio file and an optional UTI string for the file type hint. ```swift init( contentsOfURL url: URL, fileTypeHint utiString: String? ) throws ``` -------------------------------- ### Installing and Removing an Audio Tap Source: https://developer.apple.com/documentation/avfaudio/avaudionode Methods for installing and removing audio taps on a bus to monitor or record node output. ```APIDOC ## Installing and Removing an Audio Tap `func installAudioTap(onBus: AVAudioNodeBus, bufferSize: AVAudioFrameCount, format: AVAudioFormat?, tapProvider: (AVReadOnlyAudioPCMBuffer, AVAudioTime) -> Void) throws` Install a tap on a bus using a sendable block `func installTap(onBus: AVAudioNodeBus, bufferSize: AVAudioFrameCount, format: AVAudioFormat?, block: AVAudioNodeTapBlock)` Installs an audio tap on a bus you specify to record, monitor, and observe the output of the node. Deprecated `func removeTap(onBus: AVAudioNodeBus)` Removes an audio tap on a bus you specify. `typealias AVAudioNodeTapBlock` The block that receives copies of the output of an audio node. ``` -------------------------------- ### Get polarPatternSubcardioid Location Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/location/polarpatternsubcardioid Access the static property `polarPatternSubcardioid` to get the subcardioid location for audio input. This property is read-only. ```swift static var polarPatternSubcardioid: AVAudioSession.Location { get } ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudioformat/init%28commonformat%3Asamplerate%3Ainterleaved%3Achannellayout%3A%29 Creates an audio format instance with the specified audio format, sample rate, interleaved state, and channel layout. ```APIDOC ## init(commonFormat:sampleRate:interleaved:channelLayout:) ### Description Creates an audio format instance with the specified audio format, sample rate, interleaved state, and channel layout. ### Parameters - **format** (AVAudioCommonFormat) - The audio format. - **sampleRate** (Double) - The sampling rate, in hertz. - **interleaved** (Bool) - The Boolean value that indicates whether `format` is in an interleaved state. - **layout** (AVAudioChannelLayout) - The channel layout, which must not be `nil`. ### Return Value A new `AVAudioFormat` instance. ### Discussion For information about possible `format` values, see `AVAudioCommonFormat`. ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiosourcenode/init%28format%3Arenderblock%3A%29 Creates an audio source node with the audio format and a block that supplies audio data. ```APIDOC ## init(format:renderBlock:) ### Description Creates an audio source node with the audio format and a block that supplies audio data. ### Parameters #### Parameters - **format** (AVAudioFormat) - The format of the pulse-code modulated (PCM) audio data the block supplies. - **block** (@escaping AVAudioSourceNodeRenderBlock) - The block to supply audio data to the output. ### Discussion When connecting the audio source node to another node, the system uses the connection format to set the audio format for the output bus. Depending on the audio engine’s operating mode, call the block on real-time or non-real-time threads. When rendering to a device, avoid making blocking calls within the block. `AVAudioSourceNode` supports different audio formats for the block and the output, but the system only supports linear PCM conversions with sample rate, bit depth, and interleaving. ``` -------------------------------- ### Get orientationFront Property Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/location/orientationfront Access the static `orientationFront` property to get the front orientation of the audio session. This property is read-only. ```swift static var orientationFront: AVAudioSession.Location { get } ``` -------------------------------- ### Get orientationBottom Location Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/location/orientationbottom Access the static orientationBottom property to get the bottom location for an audio session. This property is read-only. ```swift static var orientationBottom: AVAudioSession.Location { get } ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/init%28data%3A%29 Creates a player to play in-memory audio data. The audio data must be in a format that Core Audio supports. ```APIDOC ## init(data: Data) throws ### Description Creates a player to play in-memory audio data. ### Parameters #### Path Parameters - **data** (Data) - Required - A buffer with the audio data to play. ### Return Value A new audio player instance, or `nil` if an error occurs. ### Discussion The audio data must be in a format that Core Audio supports. ### See Also - `init(contentsOf: URL) throws` - `init(contentsOf: URL, fileTypeHint: String?) throws` - `init(data: Data, fileTypeHint: String?) throws` ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiotime/init%28hosttime%3Asampletime%3Aatrate%3A%29 Creates an audio time object with the specified host time, sample time, and sample rate. ```APIDOC ## init(hostTime:sampleTime:atRate:) ### Description Creates an audio time object with the specified host time, sample time, and sample rate. ### Parameters - **hostTime** (UInt64) - The host time. - **sampleTime** (AVAudioFramePosition) - The sample time. - **sampleRate** (Double) - The sample rate. ### Return Value A new `AVAudioTime` instance. ### See Also - `init(audioTimeStamp: UnsafePointer, sampleRate: Double)` - `init(hostTime: UInt64)` - `init(sampleTime: AVAudioFramePosition, atRate: Double)` - `func extrapolateTime(fromAnchor: AVAudioTime) -> AVAudioTime?` ``` -------------------------------- ### prepareToPlay() Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/preparetoplay%28%29 Prepares the player for audio playback. This method preloads audio buffers and acquires the audio hardware necessary for playback. It's recommended to call this method before initiating playback to minimize delay. ```APIDOC ## Instance Method # prepareToPlay() ### Description Prepares the player for audio playback. ### Signature ```swift func prepareToPlay() -> Bool ``` ### Return Value `true` if the system successfully prepares the player; otherwise, `false`. ### Discussion Calling this method preloads audio buffers and acquires the audio hardware necessary for playback. This method activates the audio session. The system calls this method automatically when `play()` is invoked, but calling it explicitly in advance can minimize the delay between calling `play()` and the start of sound output. Calling `stop()`, or allowing a sound to finish playing, undoes this setup. ``` -------------------------------- ### Initialize AVAudioRecorder with URL and Settings Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/init%28url%3Asettings%3A%29-5whyq Use this initializer to create an audio recorder instance, specifying the file URL for recording and a dictionary of audio settings. Ensure the provided URL is a valid file system location and the settings dictionary conforms to supported audio format keys. ```swift init( url: URL, settings: [String : Any] ) throws ``` -------------------------------- ### Prepare Output Buffer and File Source: https://developer.apple.com/documentation/avfaudio/performing-offline-audio-processing Creates an `AVAudioPCMBuffer` for rendering processed audio and an `AVAudioFile` to save the output to disk. Ensure the output directory exists. ```swift // The output buffer to which the engine renders the processed data. let buffer = AVAudioPCMBuffer(pcmFormat: engine.manualRenderingFormat, frameCapacity: engine.manualRenderingMaximumFrameCount)! let outputFile: AVAudioFile do { let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] let outputURL = documentsURL.appendingPathComponent("Rhythm-processed.caf") outputFile = try AVAudioFile(forWriting: outputURL, settings: sourceFile.fileFormat.settings) } catch { fatalError("Unable to open output audio file: \(error).") } ``` -------------------------------- ### Get and Set Frequency Source: https://developer.apple.com/documentation/avfaudio/avaudiouniteqfilterparameters/frequency Use this property to get or set the frequency of the equalizer filter. The valid range is 20 Hz through (SampleRate/2). ```swift var frequency: Float { get set } ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avmidiplayer/init%28contentsof%3Asoundbankurl%3A%29 Creates a player to play a MIDI file with the specified soundbank. ```APIDOC ## init(contentsOf:soundBankURL:) ### Description Creates a player to play a MIDI file with the specified soundbank. ### Method `init(contentsOf:soundBankURL:)` ### Parameters #### Path Parameters - **inURL** (URL) - Required - The URL of the file to play. - **bankURL** (URL?) - Optional - The URL of the sound bank. The sound bank must be in SoundFont2 or DLS format. In macOS, you can pass `nil` for the bank URL argument to use the default sound bank. In iOS, you must always pass a valid bank file. ### Return Value A new MIDI player, or `nil` if an error occurred. ``` -------------------------------- ### Get Current Audio Route Description Source: https://developer.apple.com/documentation/avfaudio/avaudiosessionroutedescription Retrieve the current audio route from your app's AVAudioSession object to get an AVAudioSessionRouteDescription. ```swift var currentRoute: AVAudioSessionRouteDescription ``` -------------------------------- ### Configuring Distortion with Presets Source: https://developer.apple.com/documentation/avfaudio/avaudiounitdistortionpreset Demonstrates how to load a factory preset for an audio distortion unit. ```APIDOC ## func loadFactoryPreset(AVAudioUnitDistortionPreset) ### Description Configures the audio distortion unit by loading a distortion preset. ### Method func ### Parameters #### Path Parameters - **preset** (AVAudioUnitDistortionPreset) - Required - The distortion preset to load. ``` -------------------------------- ### Get Top Orientation Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/orientation/top Access the static `top` property to get the orientation data source that points upward. This is a constant value. ```swift static let top: AVAudioSession.Orientation ``` -------------------------------- ### Initialize AVAudioPlayer with URL Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/init%28contentsofurl%3A%29 Use this initializer to create an `AVAudioPlayer` instance from a URL. Ensure the URL points to a valid audio file. This method can throw an error if initialization fails. ```swift init(contentsOfURL url: URL) throws ``` -------------------------------- ### Get and Set primeMethod Source: https://developer.apple.com/documentation/avfaudio/avaudioconverter/primemethod This property is used to get or set the priming method for the audio converter. It is available on iOS 9.0 and later. ```swift var primeMethod: AVAudioConverterPrimeMethod { get set } ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiovoiceprocessingotheraudioduckingconfiguration/init%28enableadvancedducking%3Aduckinglevel%3A%29 Initializes an AVAudioVoiceProcessingOtherAudioDuckingConfiguration with advanced ducking settings. ```APIDOC ## init(enableAdvancedDucking:duckingLevel:) ### Description Initializes an `AVAudioVoiceProcessingOtherAudioDuckingConfiguration` object. ### Parameters - **enableAdvancedDucking** (`ObjCBool`) - A boolean value indicating whether advanced ducking is enabled. - **duckingLevel** (`AVAudioVoiceProcessingOtherAudioDuckingConfiguration.Level`) - The level of audio ducking to apply. ### Availability iOS 17.0+ iPadOS 17.0+ Mac Catalyst 17.0+ macOS 14.0+ visionOS 1.0+ ``` -------------------------------- ### Speech Activity Event Cases Source: https://developer.apple.com/documentation/avfaudio/avaudiovoiceprocessingspeechactivityevent Represents the start or end of speech activity. `started` indicates the beginning of speech, while `ended` signifies its conclusion. ```swift case started ``` ```swift case ended ``` -------------------------------- ### record(atTime:) Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/record%28attime%3A%29 Records audio starting at a specific time. This method implicitly calls prepareToRecord(). ```APIDOC ## record(atTime:) ### Description Records audio starting at a specific time. ### Method func record(atTime time: TimeInterval) -> Bool ### Parameters #### Path Parameters - **time** (TimeInterval) - Required - The time at which to start recording, relative to `deviceCurrentTime`. ### Return Value `true` if recording starts successfully; otherwise, `false`. ### Discussion You can call this method on a single recorder, or use it to synchronize the recording of multiple players. Calling this method implicitly calls `prepareToRecord()`, which creates an audio file and prepares the system for recording. ``` -------------------------------- ### Start Recording at Specific Time Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder Starts recording audio at a specified time relative to the current recording time. Returns true if successful. ```swift func record(atTime: TimeInterval) -> Bool ``` -------------------------------- ### Get and Set maximumDistance Source: https://developer.apple.com/documentation/avfaudio/avaudioenvironmentdistanceattenuationparameters/maximumdistance Use this property to get or set the distance in meters beyond which the node applies no further attenuation. The default value is 100000.0. ```swift var maximumDistance: Float { get set } ``` -------------------------------- ### Prepare AVAudioEngine Source: https://developer.apple.com/documentation/avfaudio/avaudioengine/prepare%28%29 Call this method to preallocate resources for the audio engine. Use it to ensure responsive audio input or output when starting the engine. ```swift func prepare() ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudiovoiceprocessingotheraudioduckingconfiguration/init%28%29 Initializes a new instance of AVAudioVoiceProcessingOtherAudioDuckingConfiguration. ```APIDOC ## init() ### Description Initializes a new instance of the AVAudioVoiceProcessingOtherAudioDuckingConfiguration class. ### Method `init()` ### Parameters This initializer does not take any parameters. ### Availability iOS 17.0+ iPadOS 17.0+ Mac Catalyst 17.0+ macOS 14.0+ visionOS 1.0+ ### See Also `init(enableAdvancedDucking: ObjCBool, duckingLevel: AVAudioVoiceProcessingOtherAudioDuckingConfiguration.Level)` ``` -------------------------------- ### Get and Set Bit Rate Source: https://developer.apple.com/documentation/avfaudio/avaudioconverter/bitrate Use this property to get or set the bit rate in bits per second. This value is only applied during encoding. ```swift var bitRate: Int { get set } ``` -------------------------------- ### Get and Set referenceDistance Source: https://developer.apple.com/documentation/avfaudio/avaudioenvironmentdistanceattenuationparameters/referencedistance Use this property to get or set the minimum distance in meters at which the node applies attenuation. The default value is 1.0 meter. ```swift var referenceDistance: Float { get set } ``` -------------------------------- ### init(standardFormatWithSampleRate:channels:) Source: https://developer.apple.com/documentation/avfaudio/avaudioformat/init%28standardformatwithsamplerate%3Achannels%3A%29 Creates an audio format instance with the specified sample rate and channel count. The resulting format uses `AVAudioCommonFormat.pcmFormatFloat32`. ```APIDOC ## init(standardFormatWithSampleRate:channels:) ### Description Creates an audio format instance with the specified sample rate and channel count. ### Method Signature ```swift init?(standardFormatWithSampleRate sampleRate: Double, channels: AVAudioChannelCount) ``` ### Parameters #### Parameters - **sampleRate** (Double) - The sampling rate, in hertz. - **channels** (AVAudioChannelCount) - The channel count. ### Return Value A new `AVAudioFormat` instance, or `nil` if the initialization fails. ### Discussion The returned `AVAudioFormat` instance uses the `AVAudioCommonFormat.pcmFormatFloat32` format. ### See Also - `var sampleRate: Double` - `var channelLayout: AVAudioChannelLayout?` - `init(standardFormatWithSampleRate: Double, channelLayout: AVAudioChannelLayout)` - `init?(commonFormat: AVAudioCommonFormat, sampleRate: Double, channels: AVAudioChannelCount, interleaved: Bool)` - `init(commonFormat: AVAudioCommonFormat, sampleRate: Double, interleaved: Bool, channelLayout: AVAudioChannelLayout)` - `init?(settings: [String : Any])` - `init?(streamDescription: UnsafePointer)` - `init?(streamDescription: UnsafePointer, channelLayout: AVAudioChannelLayout?) - `init?(formatDescription: CMAudioFormatDescription)` - `init(cmAudioFormatDescription: CMAudioFormatDescription) ``` -------------------------------- ### init(contentsOf:) Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/init%28contentsof%3A%29 Creates a player to play audio from a file. The audio data must be in a format that Core Audio supports. ```APIDOC ## init(contentsOf:) ### Description Creates a player to play audio from a file. ### Method `init(contentsOf url: URL) throws` ### Parameters #### Path Parameters - **url** (URL) - Required - A URL that identifies the local audio file to play. ### Return Value A new audio player instance, or `nil` if an error occurs. ### Discussion The audio data must be in a format that Core Audio supports. ### See Also - `init(contentsOf: URL, fileTypeHint: String?) throws` - `init(data: Data) throws` - `init(data: Data, fileTypeHint: String?) throws` ``` -------------------------------- ### Calculate Quantized Start Time Source: https://developer.apple.com/documentation/avfaudio/building-an-audio-sequencer-to-arrange-and-play-clips Calculates the next quantized start time for a clip based on the current time, transport start time, and tempo. Handles the initial clip launch by scheduling playback one bar in the future. For subsequent clips, it snaps to the nearest bar boundary within a tolerance. ```swift func quantizedStart( nowSeconds: Double, transportStartSeconds: Double?, tempo: Double ) -> QuantizedStart { let secPerBar = secondsPerBar(tempo: tempo) guard let startSeconds = transportStartSeconds else { // For the first clip, start one quantization period in the future. let offset = secPerBar * quantizationBars return QuantizedStart( offsetSeconds: offset, newTransportStart: nowSeconds + offset ) } let elapsed = nowSeconds - startSeconds let barsElapsed = elapsed / secPerBar let quantizedBars = barsElapsed / quantizationBars // Check if the time is within the tolerance of a bar boundary. let fractionalPart = quantizedBars - floor(quantizedBars) let nextBar: Double if fractionalPart < Self.barSnapTolerance { // If the time is just past a boundary, snap to the current bar then start immediately. nextBar = floor(quantizedBars) * quantizationBars } else if fractionalPart > (1.0 - Self.barSnapTolerance) { // If the time is just before the next boundary, snap to the next bar. nextBar = ceil(quantizedBars) * quantizationBars } else { // Wait for the next bar. nextBar = ceil(quantizedBars) * quantizationBars } let targetSeconds = startSeconds + nextBar * secPerBar let offset = max(0, targetSeconds - nowSeconds) return QuantizedStart( offsetSeconds: offset, newTransportStart: startSeconds // Unchanged. ) } ``` -------------------------------- ### Get and Set masterGain Source: https://developer.apple.com/documentation/avfaudio/avaudiounitsampler/mastergain Access the masterGain property to get or set the gain adjustment for all played notes in decibels. This property is deprecated; use overallGain instead. ```swift var masterGain: Float { get set } ``` -------------------------------- ### Start Recording at a Specific Time Source: https://developer.apple.com/documentation/avfaudio/avaudiorecorder/record%28attime%3A%29 Use this method to begin recording audio at a designated time, relative to deviceCurrentTime. It implicitly prepares the recorder and creates an audio file. ```swift func record(atTime time: TimeInterval) -> Bool ``` -------------------------------- ### Prepare AVAudioPlayer for Playback Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/preparetoplay%28%29 Call this method to preload audio buffers and acquire necessary audio hardware. It activates the audio session and should be called in advance of play() to minimize startup delay. Calling stop() or finishing playback undoes this setup. ```swift func prepareToPlay() -> Bool ``` -------------------------------- ### Get and Set delayTime Source: https://developer.apple.com/documentation/avfaudio/avaudiounitdelay/delaytime Use this property to get or set the delay time in seconds. The valid range is 0 to 2 seconds. The default value is 1. ```swift var delayTime: TimeInterval { get set } ``` -------------------------------- ### Getting and Setting Stereo Panning Source: https://developer.apple.com/documentation/avfaudio/avaudiostereomixing Use the 'pan' property to get or set the stereo pan of an audio bus. This property is required for types conforming to AVAudioStereoMixing. ```swift var pan: Float ``` -------------------------------- ### Initializer Source: https://developer.apple.com/documentation/avfaudio/avaudioplayer/init%28contentsofurl%3A%29 Initializes an audio player with the contents of a URL. This method may throw an error if the URL is invalid or the audio file cannot be loaded. ```APIDOC ## init(contentsOfURL:) ### Description Initializes an audio player with the contents of a URL. ### Method Signature ```swift init(contentsOfURL url: URL) throws ``` ### Parameters * **url** (URL) - The URL of the audio file to be played. ``` -------------------------------- ### Get and Set Velocity Source: https://developer.apple.com/documentation/avfaudio/avextendednoteonevent/velocity Use this property to get or set the MDI velocity for an event. The valid range depends on the destination audio unit, usually between 0.0 and 127.0. ```swift var velocity: Float { get set } ``` -------------------------------- ### Initializers Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/portoverride Initializers for the AVAudioSession.PortOverride enumeration. ```APIDOC ## AVAudioSession.PortOverride Initializers ### `init?(rawValue: UInt)` Initializes the enumeration case with a raw value. ``` -------------------------------- ### Get Current Audio Route Description Source: https://developer.apple.com/documentation/avfaudio/avaudiosession/currentroute Access the currentRoute property to get a description of the audio session's current input and output ports. This property is read-only. ```swift var currentRoute: AVAudioSessionRouteDescription { get } ```