AKAudioFile

@objc open class AKAudioFile: AVAudioFile

Audio file, inherits from AVAudioFile and adds functionality

  • Common places for files

    • Temp: Temp Directory
    • Documents: Documents Directory
    • Resources: Resources Directory (Shouldn’t be used for writing / recording files)
    • Custom: The same directory as the input file. This is mainly for OS X projects.
    See more

    Declaration

    Swift

    public enum BaseDirectory
  • Returns an AVAsset from the AKAudioFile

    Declaration

    Swift

    open var avAsset: AVURLAsset
  • Returns audio data as an Array of Float Arrays.

    If stereo: - floatChannelData?[0] will contain an Array of left channel samples as Float - floatChannelData?[1] will contains an Array of right channel samples as Float

    Declaration

    Swift

    open lazy var floatChannelData: FloatChannelData? =
  • returns audio data as an AVAudioPCMBuffer

    Declaration

    Swift

    open lazy var pcmBuffer: AVAudioPCMBuffer =
  • returns the peak level expressed in dB ( -> Float).

    Declaration

    Swift

    open lazy var maxLevel: Float =
  • Initialize the audio file

    Declaration

    Swift

    public override init(forReading fileURL: URL) throws

    Parameters

    fileURL

    URL of the file

    Return Value

    An initialized AKAudioFile object for reading, or nil if init failed.

  • Initialize the audio file

    • Parameters:

      • fileURL: URL of the file
      • format: The processing commonFormat to use when reading from the file.
      • interleaved: Whether to use an interleaved processing format.

    Declaration

    Swift

    public override init(forReading fileURL: URL,
                             commonFormat format: AVAudioCommonFormat,
                             interleaved: Bool) throws

    Parameters

    fileURL

    URL of the file

    format

    The processing commonFormat to use when reading from the file.

    interleaved

    Whether to use an interleaved processing format.

    Return Value

    An initialized AKAudioFile object for reading, or nil if init failed.

  • Initialize the audio file

    From Apple doc: The file type to create is inferred from the file extension of fileURL. This method will overwrite a file at the specified URL if a file already exists.

    The file is opened for writing using the standard format, AVAudioPCMFormatFloat32.

    Note: It seems that Apple’s AVAudioFile class has a bug with .wav files. They cannot be set with a floating Point encoding. As a consequence, such files will fail to record properly. So it’s better to use .caf (or .aif) files for recording purpose.

  • Parameters:

    • fileURL: URL of the file.
    • settings: The format of the file to create.
    • format: The processing commonFormat to use when writing.
    • interleaved: Whether to use an interleaved processing format.
  • Throws

    NSError if init failed

    Declaration

    Swift

    public override init(forWriting fileURL: URL,
                             settings: [String : Any],
                             commonFormat format: AVAudioCommonFormat,
                             interleaved: Bool) throws

    Parameters

    fileURL

    URL of the file.

    settings

    The format of the file to create.

    format

    The processing commonFormat to use when writing.

    interleaved

    Whether to use an interleaved processing format.

    Return Value

    An initialized AKAudioFile for writing, or nil if init failed.

  • Super.init inherited from AVAudioFile superclass

  • Parameters:

    • fileURL: URL of the file.
    • settings: The settings of the file to create.
  • Returns

    An initialized AKAudioFile for writing, or nil if init failed.

    From Apple doc: The file type to create is inferred from the file extension of fileURL. This method will overwrite a file at the specified URL if a file already exists.

    The file is opened for writing using the standard format, AVAudioPCMFormatFloat32.

    Note: It seems that Apple’s AVAudioFile class has a bug with .wav files. They cannot be set with a floating Point encoding. As a consequence, such files will fail to record properly. So it’s better to use .caf (or .aif) files for recording purpose.

    Declaration

    Swift

    public override init(forWriting fileURL: URL, settings: [String: Any]) throws

    Parameters

    fileURL

    URL of the file.

    settings

    The settings of the file to create.

    Return Value

    An initialized AKAudioFile for writing, or nil if init failed.

  • Create an AKSampler loaded with the current AKAudioFile

    Declaration

    Swift

    public var sampler: AKSampler?
  • Create an AKMIDISampler loaded with the current AKAudioFile

    Declaration

    Swift

    public var midiSampler: AKMIDISampler?
  • Create an AKAudioPlayer to play the current AKAudioFile

    Declaration

    Swift

    public var player: AKAudioPlayer?
  • Normalize an AKAudioFile to have a peak of newMaxLevel dB.

    • Parameters:

      • baseDir: where the file will be located, can be set to .resources, .documents or .temp
      • name: the name of the file without its extension (String). If none is given, a unique random name is used.
      • newMaxLevel: max level targeted as a Float value (default if 0 dB)

    Declaration

    Swift

    public func normalized(baseDir: BaseDirectory = .temp,
                               name: String = UUID().uuidString,
                               newMaxLevel: Float = 0.0 ) throws -> AKAudioFile

    Parameters

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp

    name

    the name of the file without its extension (String). If none is given, a unique random name is used.

    newMaxLevel

    max level targeted as a Float value (default if 0 dB)

    Return Value

    An AKAudioFile, or nil if init failed.

  • Returns an AKAudioFile with audio reversed (will playback in reverse from end to beginning).

  • Parameters:

    • baseDir: where the file will be located, can be set to .resources, .documents or .temp
    • name: the name of the file without its extension (String). If none is given, a unique random name is used.
  • Returns

    An AKAudioFile, or nil if init failed.

    Declaration

    Swift

    public func reversed(baseDir: BaseDirectory = .temp,
                             name: String = UUID().uuidString ) throws -> AKAudioFile

    Parameters

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp

    name

    the name of the file without its extension (String). If none is given, a unique random name is used.

    Return Value

    An AKAudioFile, or nil if init failed.

  • Returns an AKAudioFile with appended audio data from another AKAudioFile.

    Notice that Source file and appended file formats must match.

  • Parameters:

    • file: an AKAudioFile that will be used to append audio from.
    • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
    • name: the name of the file without its extension (String). If none is given, a unique random name is used.
  • Returns

    An AKAudioFile, or nil if init failed.

    Declaration

    Swift

    public func appendedBy(file: AKAudioFile,
                               baseDir: BaseDirectory = .temp,
                               name: String = UUID().uuidString) throws -> AKAudioFile

    Parameters

    file

    an AKAudioFile that will be used to append audio from.

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp

    name

    the name of the file without its extension (String). If none is given, a unique random name is used.

    Return Value

    An AKAudioFile, or nil if init failed.

  • Returns an AKAudioFile that will contain a range of samples from the current AKAudioFile

  • Parameters:

    • fromSample: the starting sampleFrame for extraction.
    • toSample: the ending sampleFrame for extraction
    • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
    • name: the name of the file without its extension (String). If none is given, a unique random name is used.
  • Returns

    An AKAudioFile, or nil if init failed.

    Declaration

    Swift

    public func extracted(fromSample: Int64 = 0,
                              toSample: Int64 = 0,
                              baseDir: BaseDirectory = .temp,
                              name: String = UUID().uuidString) throws -> AKAudioFile

    Parameters

    fromSample

    the starting sampleFrame for extraction.

    toSample

    the ending sampleFrame for extraction

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp

    name

    the name of the file without its extension (String). If none is given, a unique random name is used.

    Return Value

    An AKAudioFile, or nil if init failed.

  • Returns a silent AKAudioFile with a length set in samples.

    For a silent file of one second, set samples value to 44100…

  • Parameters:

    • samples: the number of samples to generate (equals length in seconds multiplied by sample rate)
    • baseDir: where the file will be located, can be set to .resources, .documents or .temp
    • name: the name of the file without its extension (String).
  • Returns

    An AKAudioFile, or nil if init failed.

    Declaration

    Swift

    static public func silent(samples: Int64,
                                  baseDir: BaseDirectory = .temp,
                                  name: String = "") throws -> AKAudioFile

    Parameters

    samples

    the number of samples to generate (equals length in seconds multiplied by sample rate)

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp

    name

    the name of the file without its extension (String).

    Return Value

    An AKAudioFile, or nil if init failed.

  • Opens a file for reading.

    Declaration

    Swift

    public convenience init(readFileName name: String,
                                baseDir: BaseDirectory = .resources) throws

    Parameters

    name

    Filename, including the extension

    baseDir

    Location of file, can be set to .Resources, .Documents or .Temp

    Return Value

    An initialized AKAudioFile for reading, or nil if init failed

  • Initialize file for recording / writing purpose

    Default is a .caf AKAudioFile with AudioKit settings If file name is an empty String, a unique Name will be set If no baseDir is set, baseDir will be the Temp Directory

    From Apple doc: The file type to create is inferred from the file extension of fileURL. This method will overwrite a file at the specified URL if a file already exists.

    Note: It seems that Apple’s AVAudioFile class has a bug with .wav files. They cannot be set with a floating Point encoding. As a consequence, such files will fail to record properly. So it’s better to use .caf (or .aif) files for recording purpose.

    Example of use: to create a temp .caf file with a unique name for recording: let recordFile = AKAudioFile()

    • Parameters:
      • name: the name of the file without its extension (String).
      • ext: the extension of the file without . (String).
      • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
      • settings: The settings of the file to create.
      • format: The processing commonFormat to use when writing.
      • interleaved: Bool (Whether to use an interleaved processing format.)

    Declaration

    Swift

    public convenience init(writeIn baseDir: BaseDirectory = .temp,
                                name: String? = nil,
                                settings: [String : Any] = AKSettings.audioFormat.settings)
            throws

    Parameters

    name

    the name of the file without its extension (String).

    ext

    the extension of the file without “.” (String).

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp

    settings

    The settings of the file to create.

    format

    The processing commonFormat to use when writing.

    interleaved

    Bool (Whether to use an interleaved processing format.)

  • Instantiate a file from Floats Arrays.

    To create a stereo file, you pass [leftChannelFloats, rightChannelFloats] where leftChannelFloats and rightChannelFloats are 2 arrays of FLoat values. Arrays must both have the same number of Floats.

  • Parameters:

    • floatsArrays: An array of Arrays of floats
    • name: the name of the file without its extension (String).
    • baseDir: where the file will be located, can be set to .resources, .documents or .temp
  • Returns

    a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)

    Declaration

    Swift

    public convenience init(createFileFromFloats floatsArrays: [[Float]],
                                baseDir: BaseDirectory = .temp,
                                name: String = "") throws

    Parameters

    floatsArrays

    An array of Arrays of floats

    name

    the name of the file without its extension (String).

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp

    Return Value

    a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)

  • Convenience init to instantiate a file from an AVAudioPCMBuffer.

  • Parameters:

    • buffer: the AVAudioPCMBuffer that will be used to fill the AKAudioFile
    • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp
    • name: the name of the file without its extension (String).
  • Returns

    a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)

    Declaration

    Swift

    public convenience init(fromAVAudioPCMBuffer buffer: AVAudioPCMBuffer,
                                baseDir: BaseDirectory = .temp,
                                name: String = "") throws

    Parameters

    buffer

    the AVAudioPCMBuffer that will be used to fill the AKAudioFile

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp

    name

    the name of the file without its extension (String).

    Return Value

    a .caf AKAudioFile set to AudioKit settings (32 bits float @ 44100 Hz)

  • ExportFormat enum to set target format when exporting AKAudiofiles

    • wav: Waveform Audio File Format (WAVE, or more commonly known as WAV due to its filename extension)
    • aif: Audio Interchange File Format
    • mp4: MPEG-4 Part 14 Compression
    • m4a: MPEG 4 Audio
    • caf: Core Audio Format
    See more

    Declaration

    Swift

    public enum ExportFormat
  • Returns the remaining not completed queued Async processes (Int)

    Declaration

    Swift

    static public var queuedAsyncProcessCount: Int
  • Returns the total scheduled Async processes count (Int)

    Declaration

    Swift

    static public var scheduledAsyncProcessesCount: Int
  • Returns the completed Async processes count (Int)

    Declaration

    Swift

    static public var completedAsyncProcessesCount: Int
  • Process the current AKAudioFile in background to return an AKAudioFile normalized with a peak of newMaxLevel dB if succeeded

    Completion Handler is function with an AKAudioFile.AsyncProcessCallback signature: func myCallback(processedFile: AKAudioFile?, error: NSError?) -> Void

    in this callback, you can check that process succeeded by testing processedFile value : . if processedFile != nil, process succeded (and error is nil) . if processedFile == nil, process failed, error is the process thrown error

    Notice that completionCallBack will be triggered from a background thread. Any UI update should be made using:

    dispatch_async(dispatch_get_main_queue()) {
      // UI updates...
    }
    
    • Parameters:
      • completionHandler: the callback that will be triggered when process has been completed
      • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)
      • name: the name of the resulting file without its extension (String).
      • newMaxLevel: max level targeted as a Float value (default if 0 dB)
      • completionCallBack : AKCallback that will be triggered as soon as process has been completed or failed.

    Declaration

    Swift

    public func normalizeAsynchronously(baseDir: BaseDirectory = .temp,
                                            name: String = "",
                                            newMaxLevel: Float = 0.0,
                                            completionHandler: @escaping AsyncProcessCallback)

    Parameters

    completionHandler

    the callback that will be triggered when process has been completed

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)

    name

    the name of the resulting file without its extension (String).

    newMaxLevel

    max level targeted as a Float value (default if 0 dB)

    completionCallBack

    AKCallback that will be triggered as soon as process has been completed or failed.

  • Process the current AKAudioFile in background to return the current AKAudioFile reversed (will play backward)

    Completion Handler is function with an AKAudioFile.AsyncProcessCallback signature: func myCallback(processedFile: AKAudioFile?, error: NSError?) -> Void

    in this callback, you can check that process succeeded by testing processedFile value : . if processedFile != nil, process succeded (and error is nil) . if processedFile == nil, process failed, error is the process thrown error

    Notice that completionCallBack will be triggered from a background thread. Any UI update should be made using:

    dispatch_async(dispatch_get_main_queue()) {
      // UI updates...
    }
    
    • Parameters:
      • completionHandler: the callback that will be triggered when process has been completed
      • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)
      • name: the name of the resulting file without its extension (String).
      • completionCallBack : AKCallback that will be triggered as soon as process has been completed or failed.

    Declaration

    Swift

    public func reverseAsynchronously(baseDir: BaseDirectory = .temp,
                                          name: String = "",
                                          completionHandler: @escaping AsyncProcessCallback)

    Parameters

    completionHandler

    the callback that will be triggered when process has been completed

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)

    name

    the name of the resulting file without its extension (String).

    completionCallBack

    AKCallback that will be triggered as soon as process has been completed or failed.

  • Process an AKAudioFile in background to return an AKAudioFile with appended audio data from another AKAudioFile.

    Completion Handler is function with an AKAudioFile.AsyncProcessCallback signature: func myCallback(processedFile: AKAudioFile?, error: NSError?) -> Void

    in this callback, you can check that process succeeded by testing processedFile value : . if processedFile != nil, process succeded (and error is nil) . if processedFile == nil, process failed, error is the process thrown error

    Notice that completionCallBack will be triggered from a background thread. Any UI update should be made using:

    dispatch_async(dispatch_get_main_queue()) {
      // UI updates...
    }
    
    • Parameters:
      • completionHandler: the callback that will be triggered when process has been completed
      • file: an AKAudioFile that will be used to append audio from.
      • baseDir: where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)
      • name: the name of the resulting file without its extension (String).
      • completionCallBack : AKCallback that will be triggered as soon as process has been completed or failed.

    Declaration

    Swift

    public func appendAsynchronously(file: AKAudioFile,
                                         baseDir: BaseDirectory = .temp,
                                         name: String = "",
                                         completionHandler: @escaping AsyncProcessCallback)

    Parameters

    completionHandler

    the callback that will be triggered when process has been completed

    file

    an AKAudioFile that will be used to append audio from.

    baseDir

    where the file will be located, can be set to .Resources, .Documents or .Temp (Default is .Temp)

    name

    the name of the resulting file without its extension (String).

    completionCallBack

    AKCallback that will be triggered as soon as process has been completed or failed.

  • Process the current AKAudioFile in background to return an AKAudioFile with an extracted range of audio data.

    if toSample parameter is set to zero, it will be set to be the number of samples of the file, so extraction will go from fromSample value to the end of file.

    Completion Handler is function with an AKAudioFile.AsyncProcessCallback signature: func myCallback(processedFile: AKAudioFile?, error: NSError?) -> Void

    in this callback, you can check that process succeeded by testing processedFile value : . if processedFile != nil, process succeded (and error is nil) . if processedFile == nil, process failed, error is the process thrown error

    Notice that completionCallBack will be triggered from a background thread. Any UI update should be made using:

    dispatch_async(dispatch_get_main_queue()) {
      // UI updates...
    }
    
    • Parameters:
      • completionHandler: the callback that will be triggered when process has been completed
      • fromSample: the starting sampleFrame for extraction. (default is zero)
      • toSample: the ending sampleFrame for extraction (default is zero)
      • baseDir: where the file will be located, can be set to .resources, .documents or .temp (Default is .temp)
      • name: the name of the resulting file without its extension (String).
      • completionCallBack : AKCallback that will be triggered as soon as process has been completed or failed.

    Declaration

    Swift

    public func extractAsynchronously(fromSample: Int64 = 0,
                                          toSample: Int64 = 0,
                                          baseDir: BaseDirectory = .temp,
                                          name: String = "",
                                          completionHandler: @escaping AsyncProcessCallback)

    Parameters

    completionHandler

    the callback that will be triggered when process has been completed

    fromSample

    the starting sampleFrame for extraction. (default is zero)

    toSample

    the ending sampleFrame for extraction (default is zero)

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp (Default is .temp)

    name

    the name of the resulting file without its extension (String).

    completionCallBack

    AKCallback that will be triggered as soon as process has been completed or failed.

  • Exports Asynchronously to a new AKAudiofile with trimming options.

    Can export from wav/aif/caf to wav/aif/m4a/mp4/caf Can export from m4a/mp4 to m4a/mp4 Exporting from a compressed format to a PCM format (mp4/m4a to wav/aif/caf) is not supported.

    fromSample and toSample can be set to extract only a portion of the current AKAudioFile. If toSample is zero, it will be set to the file’s duration (no end trimming)

    As soon as callback has been triggered, you can use ExportSession.status to check if export succeeded or not. If export succeeded, you can get the exported AKAudioFile using ExportSession.exportedAudioFile. ExportSession.progress lets you monitor export progress.

    See playground for an example of use.

    • Parameters:
      • name: the name of the exported file without its extension (String).
      • baseDir: where the file will be located, can be set to .resources, .documents or .temp
      • ExportFormat: the output file format as an ExportFormat enum value (.aif, .wav, .m4a, .mp4, .caf)
      • fromSample: start range in samples
      • toSample: end range time in samples
      • callback: AsyncProcessCallback function that will be triggered when export completed.

    Declaration

    Swift

    public func exportAsynchronously(name: String,
                                         baseDir: BaseDirectory,
                                         exportFormat: ExportFormat,
                                         fromSample: Int64 = 0,
                                         toSample: Int64 = 0,
                                         callback: @escaping AsyncProcessCallback)

    Parameters

    name

    the name of the exported file without its extension (String).

    baseDir

    where the file will be located, can be set to .resources, .documents or .temp

    ExportFormat

    the output file format as an ExportFormat enum value (.aif, .wav, .m4a, .mp4, .caf)

    fromSample

    start range in samples

    toSample

    end range time in samples

    callback

    AsyncProcessCallback function that will be triggered when export completed.