本文介绍了播放AVCaptureAudioDataOutputSampleBufferDelegate中的音频的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用AVCaptureAudioDataOutputSampleBufferDelegate捕获音频

I'm capturing audio using AVCaptureAudioDataOutputSampleBufferDelegate

  _captureSession = [[AVCaptureSession alloc] init];
  [self.captureSession setSessionPreset:AVCaptureSessionPresetLow];


  // Setup Audio input
  AVCaptureDevice *audioDevice = [AVCaptureDevice
                                defaultDeviceWithMediaType:AVMediaTypeAudio];
  AVCaptureDeviceInput *captureAudioInput = [AVCaptureDeviceInput deviceInputWithDevice:audioDevice error:&error];
  if(error){
      NSLog(@"Error Start capture Audio=%@", error);
  }else{
      if ([self.captureSession canAddInput:captureAudioInput]){
          [self.captureSession addInput:captureAudioInput];
      }
  }


  // Setup Audio output
  AVCaptureAudioDataOutput *audioCaptureOutput = [[AVCaptureAudioDataOutput alloc] init];
  if ([self.captureSession canAddOutput:audioCaptureOutput]){
      [self.captureSession addOutput:audioCaptureOutput];
  }
  [audioCaptureOutput release];


  //We create a serial queue 
  dispatch_queue_t audioQueue= dispatch_queue_create("audioQueue", NULL);
  [audioCaptureOutput setSampleBufferDelegate:self queue:audioQueue];
  dispatch_release(audioQueue);


  /*We start the capture*/
  [self.captureSession startRunning];

委托:

  - (void)captureOutput:(AVCaptureOutput *)captureOutput  didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

  // do something with sampleBuffer
  }

问题是如何从sampleBuffer播放音频?

The question is how can i play audio from sampleBuffer?

推荐答案

您可以使用以下命令从 CMSampleBufferRef 创建 NSData 代码然后用AVAudioPlayer播放。

You can create NSData from the CMSampleBufferRef using the following code and then play it with AVAudioPlayer.

- (void)captureOutput:(AVCaptureOutput *)captureOutput  didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer fromConnection:(AVCaptureConnection *)connection {

    AudioBufferList audioBufferList;
    NSMutableData *data= [NSMutableData data];
    CMBlockBufferRef blockBuffer;
    CMSampleBufferGetAudioBufferListWithRetainedBlockBuffer(sampleBuffer, NULL, &audioBufferList, sizeof(audioBufferList), NULL, NULL, 0, &blockBuffer);

    for( int y=0; y< audioBufferList.mNumberBuffers; y++ ){

        AudioBuffer audioBuffer = audioBufferList.mBuffers[y];
        Float32 *frame = (Float32*)audioBuffer.mData;

        [data appendBytes:frame length:audioBuffer.mDataByteSize];

    }

    CFRelease(blockBuffer);

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithData:data error:nil];
    [player play];
}

我担心这会如何表现性能。可能有更好的方法来完成你想要完成的任务。

I'm worried about how this will do performance wise though. There probably is a better way to do what you are trying to accomplish.

这篇关于播放AVCaptureAudioDataOutputSampleBufferDelegate中的音频的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-22 00:10