我想在我的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)
但是出现了这个错误
无法赋值:函数调用返回不可变值
有什么想法吗?
答案 0 :(得分:5)
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)")
}
}