使用特定采样率捕获音频样本,如 iOS Swift 中的 Android

Moh*_*lah 5 pcm avfoundation ios swift avaudioengine

我是在 IOS 中使用声音和 AVAudioEngine 的初学者,我正在开发一个应用程序,将音频样本捕获为缓冲区并对其进行分析。此外,采样率必须为 8000 kHz,也必须编码为 PCM16Bit,但 AVAudioEngine 中的默认 inputNode 为 44.1 kHz。

在 Android 中,过程非常简单:

AudioRecord audioRecord = new AudioRecord(MediaRecorder.AudioSource.MIC,
                8000, AudioFormat.CHANNEL_IN_MONO,
                AudioFormat.ENCODING_PCM_16BIT, bufferSize);
Run Code Online (Sandbox Code Playgroud)

然后启动缓冲区的读取功能。我搜索了很多,但没有找到任何类似的例子。相反,我遇到的所有示例都以默认节点的采样率(44.1 kHz)捕获样本,例如:

    let input = audioEngine.inputNode
    let inputFormat = input.inputFormat(forBus: 0)
    input.installTap(onBus: 0, bufferSize: 640, format: inputFormat) { (buffer, time) -> Void in
                print(inputFormat)
                if let channel1Buffer = buffer.floatChannelData?[0] {
                    for i in 0...Int(buffer.frameLength-1) {
                        print(channel1Buffer[i])
                    }
                }
            }
try! audioEngine.start()
Run Code Online (Sandbox Code Playgroud)

所以我想使用 AVAudioEngine 以 8000 kHz 采样率和 PCM16Bit 编码捕获音频样本。

*编辑: 我找到了将输入转换为 8 kHz 的解决方案:

    let inputNode = audioEngine.inputNode
    let downMixer = AVAudioMixerNode()
    let main = audioEngine.mainMixerNode

    let format = inputNode.inputFormat(forBus: 0)
    let format16KHzMono = AVAudioFormat(commonFormat: AVAudioCommonFormat.pcmFormatInt16, sampleRate: 8000, channels: 1, interleaved: true)

    audioEngine.attach(downMixer)
    downMixer.installTap(onBus: 0, bufferSize: 640, format: format16KHzMono) { (buffer, time) -> Void in
        do{
            print(buffer.description)
            if let channel1Buffer = buffer.int16ChannelData?[0] {
                // print(channel1Buffer[0])
                for i in 0 ... Int(buffer.frameLength-1) {
                    print((channel1Buffer[i]))
                }
            }
        }
    }

    audioEngine.connect(inputNode, to: downMixer, format: format)
    audioEngine.connect(downMixer, to: main, format: format16KHzMono)
    audioEngine.prepare()
    try! audioEngine.start()
Run Code Online (Sandbox Code Playgroud)

,但是当我使用.pcmFormatInt16它时不起作用。但是,当我使用.pcmFormatFloat32它时效果很好!

谢谢,,

Pra*_* Sp 3

你检查过settings参数 吗

let format16KHzMono = AVAudioFormat(settings: [AVFormatIDKey: AVAudioCommonFormat.pcmFormatInt16,
                                                               AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue,
                                                               AVEncoderBitRateKey: 16,
                                                               AVNumberOfChannelsKey: 1,
                                                               AVSampleRateKey: 8000.0] as [String : AnyObject])
Run Code Online (Sandbox Code Playgroud)

  • 事实上,我已经找到了解决方案,但是赏金将在 15 小时后过期。所以,因为您是唯一回答这个问题的人,所以您应得的。 (2认同)