2017-05-28 121 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] 
}