8

我有两个班级MicrophoneHandler, 和AudioPlayer。我已经设法使用此处AVCaptureSession批准的答案来窃听麦克风数据,并将其转换为使用此功能:CMSampleBufferNSData

func sendDataToDelegate(buffer: CMSampleBuffer!)
{
    let block = CMSampleBufferGetDataBuffer(buffer)
    var length = 0
    var data: UnsafeMutablePointer<Int8> = nil

    var status = CMBlockBufferGetDataPointer(block!, 0, nil, &length, &data)    // TODO: check for errors

    let result = NSData(bytesNoCopy: data, length: length, freeWhenDone: false)

    self.delegate.handleBuffer(result)
}

我现在想通过将NSData上面生成的音频转换为AVAudioPCMBuffer并使用AVAudioEngine. 我的AudioPlayer班级如下:

var engine: AVAudioEngine!
var playerNode: AVAudioPlayerNode!
var mixer: AVAudioMixerNode!

override init()
{
    super.init()

    self.setup()
    self.start()
}

func handleBuffer(data: NSData)
{
    let newBuffer = self.toPCMBuffer(data)
    print(newBuffer)

    self.playerNode.scheduleBuffer(newBuffer, completionHandler: nil)
}

func setup()
{
    self.engine = AVAudioEngine()
    self.playerNode = AVAudioPlayerNode()

    self.engine.attachNode(self.playerNode)
    self.mixer = engine.mainMixerNode

    engine.connect(self.playerNode, to: self.mixer, format: self.mixer.outputFormatForBus(0))
}

func start()
{
    do {
        try self.engine.start()
    }
    catch {
        print("error couldn't start engine")
    }

    self.playerNode.play()
}

func toPCMBuffer(data: NSData) -> AVAudioPCMBuffer
{
    let audioFormat = AVAudioFormat(commonFormat: AVAudioCommonFormat.PCMFormatFloat32, sampleRate: 8000, channels: 2, interleaved: false)  // given NSData audio format
    let PCMBuffer = AVAudioPCMBuffer(PCMFormat: audioFormat, frameCapacity: UInt32(data.length) / audioFormat.streamDescription.memory.mBytesPerFrame)

    PCMBuffer.frameLength = PCMBuffer.frameCapacity

    let channels = UnsafeBufferPointer(start: PCMBuffer.floatChannelData, count: Int(PCMBuffer.format.channelCount))

    data.getBytes(UnsafeMutablePointer<Void>(channels[0]) , length: data.length)

    return PCMBuffer
}

缓冲区到达handleBuffer:bufferself.delegate.handleBuffer(result)在上面的第一个片段中调用函数。

我能够print(newBuffer)看到转换后的缓冲区的内存位置,但扬声器什么也没有。我只能想象到和 from 的转换之间存在一些不一致的地方NSData。有任何想法吗?提前致谢。

4

1 回答 1

2

跳过原始NSData格式

为什么不AVAudioPlayer一直使用?如果您确实需要,您可以随时从下面NSData加载此类数据。soundURL在此示例中,磁盘缓冲区类似于:

let soundURL = documentDirectory.URLByAppendingPathComponent("sound.m4a")

无论如何,为了优化内存和资源管理,直接记录到文件是有意义的。您可以NSData通过以下方式从录音中获得:

let data = NSFileManager.defaultManager().contentsAtPath(soundURL.path())

下面的代码就是你所需要的:

记录

if !audioRecorder.recording {
    let audioSession = AVAudioSession.sharedInstance()
    do {
        try audioSession.setActive(true)
        audioRecorder.record()
    } catch {}
}

if (!audioRecorder.recording){
    do {
        try audioPlayer = AVAudioPlayer(contentsOfURL: audioRecorder.url)
        audioPlayer.play()
    } catch {}
}

设置

let audioSession = AVAudioSession.sharedInstance()
do {
    try audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
    try audioRecorder = AVAudioRecorder(URL: self.directoryURL()!,
        settings: recordSettings)
    audioRecorder.prepareToRecord()
} catch {}

设置

let recordSettings = [AVSampleRateKey : NSNumber(float: Float(44100.0)),
    AVFormatIDKey : NSNumber(int: Int32(kAudioFormatMPEG4AAC)),
    AVNumberOfChannelsKey : NSNumber(int: 1),
    AVEncoderAudioQualityKey : NSNumber(int: Int32(AVAudioQuality.Medium.rawValue))]

下载 Xcode 项目:

你可以在这里找到这个例子。从Swift Recipes下载完整的项目,它可以在模拟器和设备上录制和播放。

于 2015-12-05T02:58:07.583 回答