-1

I am new to swift and working on a project where i had to visualize audio waves! I am using EZAudio pod where to plot the waves on the screen a function UpdatePlot is used and in parameter a UnsafeMutablePoiter> is passed I want the maximum value in each UnUnsafeMutablePointer to find the highest wave length on the plot

buffer[0]//with a bufferSize UInt32

I want to find the highest value in that buffer[0] array!

Please Help!!! p.s : thanks in advance

2 Answers2

0

for the array buffer[]

Swift 3:

buffer.max()

Swift 2:

buffer.maxElement()
Greg Robertson
  • 2,317
  • 1
  • 16
  • 30
0

These two lines are so confusing:

buffer[0]//with a bufferSize UInt32

I want to find the highest value in that buffer[0] array!

Which is an UnsafeMutablePointer<Float>, buffer itself or buffer[0]? Is buffer a Swift Array?

I assume buffer is of type UnsafeMutablePointer<Float>.

Manually:

func myMax(buf: UnsafePointer<Float>, count: UInt32) -> Float? {
    guard case let bufCount = Int(count) where count > 0 else {return nil}
    var max = -Float.infinity
    for i in 0..<bufCount {
        if buf[i] > max {
            max = buf[i]
        }
    }
    return max
}

Use it like this:

if let maxValue = myMax(buffer, count: bufferSize) {
    //Use the maximum value
    print(maxValue)
} else {
    //No maximum value when empty
    print("empty")
}

If you want to utilize Swift Library, you can write myMax as:

func myMax(buf: UnsafePointer<Float>, count: UInt32) -> Float? {
    return UnsafeBufferPointer(start: buf, count: Int(count)).maxElement()
}
OOPer
  • 47,149
  • 6
  • 107
  • 142