2017-05-28 78 views
0

我已经成功地使用AVAudioPlayerNode发挥立体声和单声道文件。我想在一个非线性的方式使用的文件有3个以上的通道(环绕声文件),并能够将音频传送。例如,我可以文件通道0分配给输出信道2,和文件通道4,以输出通道1AVAudioPlayerNode多声道音频控制

的音频接口的输出的数量将是未知的(2-40),这就是为什么我需要要能够让用户将音频路由,因为他们认为合适的。而在具有用户更改路由在音频MIDI设置的WWDC 2015 507的解决方案是不是一个可行的解决方案。

我想到的只有1种可能性(我对其他人开放):每个频道创建一个播放器,并且每个频道只装载一个频道的缓冲区similar to this post。但即使海报的承认,也有问题。

所以我在寻找一种方式,以一个文件的每个通道复制到一个AudioBuffer像:

let file = try AVAudioFile(forReading: audioURL) 
let fullBuffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, 
            frameCapacity: AVAudioFrameCount(file.length)) 

try file.read(into: fullBuffer) 

// channel 0 
let buffer0 = AVAudioPCMBuffer(pcmFormat: file.processingFormat, 
           frameCapacity: AVAudioFrameCount(file.length)) 

// this doesn't work, unable to get fullBuffer channel and copy 
// error on subscripting mBuffers 
buffer0.audioBufferList.pointee.mBuffers.mData = fullBuffer.audioBufferList.pointee.mBuffers[0].mData 

// repeat above buffer code for each channel from the fullBuffer 

回答

0

我能弄明白,所以这里的代码,使其工作。注意:下面的代码分隔立体声(2声道)文件。这可以轻松扩展以处理未知数量的频道。

let file = try AVAudioFile(forReading: audioURL) 

let formatL = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.processingFormat.sampleRate, channels: 1, interleaved: false) 
let formatR = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: file.processingFormat.sampleRate, channels: 1, interleaved: 

let fullBuffer = AVAudioPCMBuffer(pcmFormat: file.processingFormat, frameCapacity: AVAudioFrameCount(file.length)) 
let bufferLeft = AVAudioPCMBuffer(pcmFormat: formatL, frameCapacity: AVAudioFrameCount(file.length)) 
let bufferRight = AVAudioPCMBuffer(pcmFormat: formatR, frameCapacity: AVAudioFrameCount(file.length)) 

try file.read(into: fullBuffer) 
bufferLeft.frameLength = fullBuffer.frameLength 
bufferRight.frameLength = fullBuffer.frameLength 

for i in 0..<Int(file.length) { 
    bufferLeft.floatChannelData![0][i] = fullBuffer.floatChannelData![0][i] 
    bufferRight.floatChannelData![0][i] = fullBuffer.floatChannelData![1][i] 
}