Skip to content

Commit 84c3e01

Browse files
committed
Refactor(AVAudioFile): move logic into extension and analyze function
1 parent 9ca584e commit 84c3e01

File tree

3 files changed

+43
-16
lines changed

3 files changed

+43
-16
lines changed

Example/Pods/Pods.xcodeproj/project.pbxproj

Lines changed: 9 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
//
2+
// AVAudioFileExtensions.swift
3+
// Pods-SoundWave_Example
4+
//
5+
// Created by Bastien Falcou on 4/21/19.
6+
//
7+
8+
import AVFoundation
9+
10+
extension AVAudioFile {
11+
func buffer() throws -> [[Float]] {
12+
let format = AVAudioFormat(commonFormat: .pcmFormatFloat32,
13+
sampleRate: self.fileFormat.sampleRate,
14+
channels: self.fileFormat.channelCount,
15+
interleaved: false)
16+
let buffer = AVAudioPCMBuffer(pcmFormat: format!, frameCapacity: UInt32(self.length))!
17+
try self.read(into: buffer, frameCount: UInt32(self.length))
18+
return self.analyze(buffer: buffer)
19+
}
20+
21+
private func analyze(buffer: AVAudioPCMBuffer) -> [[Float]] {
22+
let channelCount = Int(buffer.format.channelCount)
23+
let frameLength = Int(buffer.frameLength)
24+
var result = Array(repeating: [Float](repeatElement(0, count: frameLength)), count: channelCount)
25+
for channel in 0..<channelCount {
26+
for sampleIndex in 0..<frameLength {
27+
let sqrtV = sqrt(buffer.floatChannelData![channel][sampleIndex*buffer.stride]/Float(buffer.frameLength))
28+
let dbPower = 20 * log10(sqrtV)
29+
result[channel][sampleIndex] = dbPower
30+
}
31+
}
32+
return result
33+
}
34+
}

SoundWave/Classes/AudioVisualizationView.swift

Lines changed: 0 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -150,22 +150,6 @@ public class AudioVisualizationView: BaseNibView {
150150
return self.meteringLevelsClusteredArray
151151
}
152152

153-
// PRAGMA: - Analyze Sound File
154-
155-
private func buffer(url: URL) {
156-
do {
157-
let track = try AVAudioFile(forReading: url)
158-
let format = AVAudioFormat(commonFormat:.pcmFormatFloat32,
159-
sampleRate:track.fileFormat.sampleRate,
160-
channels: track.fileFormat.channelCount,
161-
interleaved: false)
162-
let buffer = AVAudioPCMBuffer(pcmFormat: format!, frameCapacity: UInt32(track.length))!
163-
try track.read(into : buffer, frameCount:UInt32(track.length))
164-
} catch {
165-
print(error)
166-
}
167-
}
168-
169153
// PRAGMA: - Play Mode Handling
170154

171155
public func play(for duration: TimeInterval) {

0 commit comments

Comments
 (0)