Skip to content

Commit

Permalink
File length bug (#2937)
Browse files Browse the repository at this point in the history
* #2936 demonstrate bug

* #2936 handle arbitrary channel counts

* #2936 fix testReadFile

* #2936 formatting
  • Loading branch information
wtholliday authored Oct 19, 2024
1 parent de25aa2 commit c1de933
Show file tree
Hide file tree
Showing 4 changed files with 31 additions and 13 deletions.
8 changes: 7 additions & 1 deletion Sources/AudioKit/Audio Files/AVAudioFile+Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,15 @@ public extension AVAudioFile {
guard let buffer = AVAudioPCMBuffer(pcmFormat: processingFormat,
frameCapacity: AVAudioFrameCount(length)) else { return nil }

guard let tmpBuffer = AVAudioPCMBuffer(pcmFormat: processingFormat,
frameCapacity: AVAudioFrameCount(length)) else { return nil }

do {
framePosition = 0
try read(into: buffer)
while framePosition < length {
try read(into: tmpBuffer)
buffer.append(tmpBuffer)
}
Log("Created buffer with format", processingFormat)

} catch let error as NSError {
Expand Down
19 changes: 7 additions & 12 deletions Sources/AudioKit/Audio Files/AVAudioPCMBuffer+Utilities.swift
Original file line number Diff line number Diff line change
Expand Up @@ -65,19 +65,14 @@ public extension AVAudioPCMBuffer {
precondition(frameLength + frameCount <= frameCapacity,
"Insufficient space in buffer")

let dst1 = floatChannelData![0]
let src1 = buffer.floatChannelData![0]
for channel in 0..<Int(format.channelCount) {
let dst = floatChannelData![channel]
let src = buffer.floatChannelData![channel]

memcpy(dst1.advanced(by: stride * Int(frameLength)),
src1.advanced(by: stride * Int(startingFrame)),
Int(frameCount) * stride * MemoryLayout<Float>.size)

let dst2 = floatChannelData![1]
let src2 = buffer.floatChannelData![1]

memcpy(dst2.advanced(by: stride * Int(frameLength)),
src2.advanced(by: stride * Int(startingFrame)),
Int(frameCount) * stride * MemoryLayout<Float>.size)
memcpy(dst.advanced(by: stride * Int(frameLength)),
src.advanced(by: stride * Int(startingFrame)),
Int(frameCount) * stride * MemoryLayout<Float>.size)
}

frameLength += frameCount
}
Expand Down
17 changes: 17 additions & 0 deletions Tests/AudioKitTests/Extension Tests/AVAudioFileTests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import XCTest
import AVFoundation

final class AVAudioFileTests: XCTestCase {

func testReadFile() throws {

let sampleURL = Bundle.module.url(forResource: "TestResources/0001_1-16", withExtension: "wav")!

let wavFile = try AVAudioFile(forReading: sampleURL)

let pcmBuffer = wavFile.toAVAudioPCMBuffer()!

XCTAssertEqual(Int(wavFile.length), Int(pcmBuffer.frameLength))
}

}
Binary file added Tests/AudioKitTests/TestResources/0001_1-16.wav
Binary file not shown.

0 comments on commit c1de933

Please sign in to comment.