sonodrill

Sonodrill, app iOS/Android d’entraînement musical (repères, boucles, vitesse), Kotlin Multiplatform + Compose
git clone https://git.schurger.org/sonodrill.git
Log | Files | Refs

WaveformExtractor.swift (1354B)


      1 import AVFoundation
      2 import ComposeApp
      3 
      4 class SwiftWaveformProvider: WaveformProvider {
      5     func extractWaveform(path: String, numSamples: Int32) -> [Any] {
      6         let url = URL(fileURLWithPath: path)
      7         guard let file = try? AVAudioFile(forReading: url) else { return [] }
      8         let totalFrames = file.length
      9         guard totalFrames > 0 else { return [] }
     10         let format = file.processingFormat
     11         let framesPerSample = max(AVAudioFrameCount(totalFrames / Int64(numSamples)), 1)
     12         guard let buffer = AVAudioPCMBuffer(pcmFormat: format, frameCapacity: framesPerSample) else { return [] }
     13 
     14         var result: [NSNumber] = []
     15         result.reserveCapacity(Int(numSamples))
     16 
     17         for i in 0..<Int(numSamples) {
     18             file.framePosition = Int64(i) * Int64(framesPerSample)
     19             do {
     20                 try file.read(into: buffer)
     21             } catch {
     22                 break
     23             }
     24             guard let channelData = buffer.floatChannelData?[0] else { break }
     25             let count = Int(buffer.frameLength)
     26             guard count > 0 else { break }
     27             var maxVal: Float = 0
     28             for j in 0..<count {
     29                 let v = abs(channelData[j])
     30                 if v > maxVal { maxVal = v }
     31             }
     32             result.append(NSNumber(value: maxVal))
     33         }
     34         return result
     35     }
     36 }