Swift 3 AVAudioEngine设置麦克风输入格式

时间:2017-05-25 15:24:29

标签: ios swift avaudioengine

我想在我的iOS上使用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);

我试过了:

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

但是出现了这个错误

  

无法赋值:函数调用返回不可变值

有什么想法吗?

1 个答案:

答案 0 :(得分:5)

噢,天啊,我想我明白了。我太盲目了,你不能看到你可以指定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)")
    }
}