2017-05-25 60 views
1

我想處理從我的iOS上使用Swift 3從麥克風讀取的字節。我目前使用AVAudioEngine。Swift 3 AVAudioEngine設置麥克風輸入格式

print(inputNode.inputFormat(forBus: bus).settings) 
print(inputNode.inputFormat(forBus: bus).formatDescription) 

這給了我下面的輸出:

["AVNumberOfChannelsKey": 1, "AVLinearPCMBitDepthKey": 32, "AVSampleRateKey": 16000, "AVLinearPCMIsNonInterleaved": 1, "AVLinearPCMIsBigEndianKey": 0, "AVFormatIDKey": 1819304813, "AVLinearPCMIsFloatKey": 1] 
<CMAudioFormatDescription 0x14d5bbb0 [0x3a5fb7d8]> { 
    mediaType:'soun' 
    mediaSubType:'lpcm' 
    mediaSpecific: { 
     ASBD: { 
      mSampleRate: 16000.000000 
      mFormatID: 'lpcm' 
      mFormatFlags: 0x29 
      mBytesPerPacket: 4 
      mFramesPerPacket: 1 
      mBytesPerFrame: 4 
      mChannelsPerFrame: 1 
      mBitsPerChannel: 32  } 
     cookie: {(null)} 
     ACL: {(null)} 
     FormatList Array: {(null)} 
    } 
    extensions: {(null)} 
} 

的問題是,我要發送的數據的服務器並不指望32位浮點但16位無符號整數。我想我必須改變mFormatFlags。有人知道我該如何做到這一點,什麼價值纔是正確的?

由此產生的字節流應相當於使用

AudioRecord recorder = new AudioRecord(MediaRecorder.AudioSource.MIC, SAMPLES_PER_SECOND, 
      AudioFormat.CHANNEL_IN_MONO, AudioFormat.ENCODING_PCM_16BIT, 
      recordSegmentSizeBytes); 

我想這就是我得到的android:

let cfmt = AVAudioCommonFormat.pcmFormatInt16 
     inputNode.inputFormat(forBus: bus) = AVAudioFormat(commonFormat: cfmt, sampleRate: 16000.0, channels: 1, interleaved: false) 

,但得到這個錯誤

Cannot assign to value: function call returns immutable value

任何想法?

回答

3

天啊,我想我明白了。我太盲目了,看不到您可以指定installTap回調的格式。這似乎是工作

let audioEngine = AVAudioEngine() 

func startRecording() { 
    let inputNode = audioEngine.inputNode! 
    let bus = 0 

    let format = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 16000.0, channels: 1, interleaved: false) 

    inputNode.installTap(onBus: bus, bufferSize: 2048, format: format) { // inputNode.inputFormat(forBus: bus) 
     (buffer: AVAudioPCMBuffer!, time: AVAudioTime!) -> Void in 

     let values = UnsafeBufferPointer(start: buffer.int16ChannelData![0], count: Int(buffer.frameLength)) 
     let arr = Array(values) 
     print(arr) 
    } 


    audioEngine.prepare() 
    do { 
     try audioEngine.start() 
    } catch { 
     print("Error info: \(error)") 
    } 
} 
+0

這使得崩潰代碼: 錯誤:[0x3b49de40]> avae> AVAudioIONodeImpl.mm:884:SetOutputFormat:需要的條件是假的:format.sampleRate == hwFormat.sampleRate 如果你有任何soln plz發送 –