如何在iOS 11+中记录FLAC格式

时间:2018-06-21 20:07:46

标签: ios iphone swift google-speech-api flac

我将AudioController.swift中的代码更改为:

...
// Set format for mic input (bus 1) on RemoteIO's output scope
var asbd = AudioStreamBasicDescription()
...
asbd.mFormatID = kAudioFormatFLAC
asbd.mFormatFlags = kAppleLosslessFormatFlag_16BitSourceData
...

SpeechRecognitionService.swift

...
// send an initial request message to configure the service
let recognitionConfig = RecognitionConfig()
recognitionConfig.encoding =  .flac
...

我尝试修改AudioStreamBasicDescription.mFormatFlags,但找不到正确的标志来让Google Speech API识别格式。

如何使iOS使用给定的iOS API记录FLAC?

1 个答案:

答案 0 :(得分:1)

尝试

/// Common Struct 
struct Manager
{    
    //Required Objects - AVFoundation
    ///AVAudio Session
    static var recordingSession: AVAudioSession!

    ///AVAudio Recorder
    static var recorder: AVAudioRecorder?
}

权限

func CheckForPermission() {
    Manager.recordingSession = AVAudioSession.sharedInstance()
    do {
        try Manager.recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord, with: .defaultToSpeaker)
        Manager.recordingSession.requestRecordPermission({ (allowed) in
            if allowed {
                Manager.micAuthorised = true
            }
            else {
                Manager.micAuthorised = false
            }
        })
        DispatchQueue.main.async  {
            //Reload Label text in Home screen
            NotificationCenter.default.post(name: NSNotification.Name(rawValue: "updateLabel"), object: nil)
        }
    }
    catch {
        print("Failed to set Category", error.localizedDescription)
    }
}

使用flac进行记录器设置和记录

func startMainRecording() {
    print("Main Recording session is created")

    //Get unique File Name
    Manager.audioName = getUniqueName()
    let AudioFileName = getDocumentsDirectory().appendingPathComponent("\(Manager.audioName).flac")
    print("New Path: \(AudioFileName)")

    //Recorder Settings
    let settings: [String: Any] = [
        /// Format Flac
        AVFormatIDKey: Int(kAudioFormatFLAC),
        AVSampleRateKey: 16000,
        AVNumberOfChannelsKey: 1,
        AVLinearPCMBitDepthKey: 16,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
        AVLinearPCMIsBigEndianKey: false,
        AVLinearPCMIsFloatKey: false,
        ]

    //Handler
    do {
        //Activate session when required

        //try Manager.recordingSession.setPreferredSampleRate(44000)
        try Manager.recordingSession.setActive(true)

        //Start Recording With Audio File name
        Manager.recorder = try AVAudioRecorder(url: AudioFileName, settings: settings)
        Manager.recorder?.delegate = self
        Manager.recorder?.isMeteringEnabled = true
    }
    catch
    {
        //Finish Recording with a Error
        print("Error Handling: \(error.localizedDescription)")
        /// Saved here if any error occur while recording Just case
        self.finishRecording(success: false)
    }
}