Skip to content

Commit

Permalink
Merge branch 'AudioKit:main' into main
Browse files Browse the repository at this point in the history
  • Loading branch information
jcavar authored Nov 17, 2024
2 parents 7fd9b78 + c6e2489 commit f6a1b7f
Show file tree
Hide file tree
Showing 2 changed files with 60 additions and 0 deletions.
16 changes: 16 additions & 0 deletions Sources/AudioKit/Audio Files/AVAudioPCMBuffer+Processing.swift
Original file line number Diff line number Diff line change
Expand Up @@ -253,3 +253,19 @@ extension AVAudioPCMBuffer {
return value
}
}

public extension AVAudioPCMBuffer {
func mixToMono() -> AVAudioPCMBuffer {
let newFormat = AVAudioFormat(standardFormatWithSampleRate: format.sampleRate, channels: 1)!
let buffer = AVAudioPCMBuffer(pcmFormat: newFormat, frameCapacity: frameLength)!
buffer.frameLength = frameLength

let stride = vDSP_Stride(1)
let result = buffer.floatChannelData![0]
for channel in 0 ..< format.channelCount {
let channelData = self.floatChannelData![Int(channel)]
vDSP_vadd(channelData, stride, result, stride, result, stride, vDSP_Length(frameLength))
}
return buffer
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
import AudioKit
import AVFoundation
import Foundation
import XCTest

class AVAudioPCMBufferMixToMonoTests: XCTestCase {
let sampleRate: Double = 44100
lazy var capacity = 10 * UInt32(sampleRate)
lazy var format = AVAudioFormat(standardFormatWithSampleRate: sampleRate, channels: 2)!
lazy var buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: capacity)!
lazy var data = buffer.floatChannelData!

func testMixToMonoCancellation() {
for index in 0..<capacity {
data[0][Int(index)] = -1
data[1][Int(index)] = 1
}
buffer.frameLength = capacity

let mono = buffer.mixToMono()

XCTAssertEqual(mono.format.channelCount, 1)
XCTAssertEqual(mono.frameCapacity, capacity)
XCTAssertEqual(mono.frameLength, capacity)

XCTAssertTrue(mono.toFloatChannelData()![0].allSatisfy { $0 == 0 })
}

func testMixToMonoDouble() {
for index in 0..<capacity {
data[0][Int(index)] = 1
data[1][Int(index)] = 1
}
buffer.frameLength = capacity

let mono = buffer.mixToMono()

XCTAssertEqual(mono.format.channelCount, 1)
XCTAssertEqual(mono.frameCapacity, capacity)
XCTAssertEqual(mono.frameLength, capacity)

XCTAssertTrue(mono.toFloatChannelData()![0].allSatisfy { $0 == 2 })
}
}

0 comments on commit f6a1b7f

Please sign in to comment.