2017-04-06 319 views
3

我正在录制来自麦克风的音频并将该音频流式传输到其他设备。目前,即使用户不在说话时,也会通过流发送此音频。但是我注意到,很多流媒体服务在检测到来自它的噪声很少时实际上并没有发送您的麦克风输入。Swift - 如何从麦克风输入获取当前音量(AVAudioPCMBuffer)

所以我问,如何在输入到其他设备之前看到输入有多大声。

我使用连接到AVAudioEngine的AVAudioPlayerNode录制音频。然后我用下面的实际记录:

localInput?.installTap(onBus: 0, bufferSize: 4096, format: localInputFormat) { 
    (buffer, when) -> Void in 

这里,缓冲是一个AVAudioPCMBuffer,所以我需要能够看到从这个缓冲区的容量。

谢谢!

回答

1

我能得到使用下面的代码完成这件事:

  let arraySize = Int(buffer.frameLength) 
      var channelSamples: [[DSPComplex]] = [] 
      let channelCount = Int(buffer.format.channelCount) 

      for i in 0..<channelCount { 

       channelSamples.append([]) 
       let firstSample = buffer.format.isInterleaved ? i : i*arraySize 

       for j in stride(from: firstSample, to: arraySize, by: buffer.stride*2) { 

        let channels = UnsafeBufferPointer(start: buffer.floatChannelData, count: Int(buffer.format.channelCount)) 
        let floats = UnsafeBufferPointer(start: channels[0], count: Int(buffer.frameLength)) 
        channelSamples[i].append(DSPComplex(real: floats[j], imag: floats[j+buffer.stride])) 

       } 
      } 

      var spectrum = [Float]() 

      for i in 0..<arraySize/2 { 

       let imag = channelSamples[0][i].imag 
       let real = channelSamples[0][i].real 
       let magnitude = sqrt(pow(real,2)+pow(imag,2)) 

       spectrum.append(magnitude) 
      } 

信用为这个答案去这个question