Saturday, November 21, 2026
HomeiOS Developmentios - Learn how to Change Sound Wave Swift

ios – Learn how to Change Sound Wave Swift

[ad_1]

Do this code

import Basis
import AVFoundation
import Speed up


public enum WaveformStyle {
case soundcloud
}

public class WaveformZoomable : UIView {

public var zoomFactor: Float = 1.0 {
    didSet {
        if zoomFactor > 1.0 {
            zoomFactor = 1.0
        }
        else if zoomFactor < 0.01 {
            zoomFactor = 0.01
        }
    }
}

public var fashion: WaveformStyle = .soundcloud {
    didSet {
        self.reload(zoomFactor: zoomFactor)
    }
}

struct readFile {
    static var floatValuesLeft = [Float]()
    static var floatValuesRight = [Float]()
    static var leftPoints = [CGPoint]()
    static var rightPoints = [CGPoint]()
    static var populated = false
}

let pixelWidth: CGFloat = 2.0
let pixelSpacing: CGFloat = 2.0

public comfort init(withFile: URL, fashion: WaveformStyle = .soundcloud) {
    self.init()
    
    openFile(withFile)
    
    self.fashion = fashion
}

public func openFile(_ file: URL) {
    var audioFile = AVAudioFile()
    do {
        audioFile = attempt AVAudioFile(forReading: file)
    }catch{
        SVProgressHUD.showInfo(withStatus:"Error Sound File Crupted")
        return
    }
    
    // specify the format we WANT for the buffer
    let format = AVAudioFormat(commonFormat: .pcmFormatFloat32, sampleRate: audioFile.fileFormat.sampleRate, channels: audioFile.fileFormat.channelCount, interleaved: false)
    
    // initialize and fill the buffer
    let buffer = AVAudioPCMBuffer(pcmFormat: format!, frameCapacity: UInt32(audioFile.size))
    attempt! audioFile.learn(into: buffer!)
    
    // copy buffer to readFile struct
    readFile.floatValuesLeft = Array(UnsafeBufferPointer(begin: buffer?.floatChannelData?[0], rely:Int(buffer!.frameLength)))
    
    readFile.populated = true
    
    reload(zoomFactor: zoomFactor)
}

public func reload(zoomFactor: Float = 1.0) {
    self.zoomFactor = zoomFactor
    setNeedsDisplay()
}

func makePoints() {
    if !readFile.populated { return }
    
    let viewWidth = bounds.width
    
    let sampleCount = Int(Float(readFile.floatValuesLeft.rely) * zoomFactor)
    //        print(sampleCount)
    
    // seize each nth pattern (samplesPerPixel)
    let samplesPerPixel = Int(ground(Float(sampleCount) / Float(viewWidth)))
    //        print(samplesPerPixel)
    
    // the anticipated pattern rely
    let reducedSampleCount = sampleCount / samplesPerPixel
    //        print(reducedSampleCount)
    
    // left channel
    var processingBuffer = [Float](repeating: 0.0,
                                   rely: sampleCount)
    
    // get absolute values
    vDSP_vabs(readFile.floatValuesLeft, 1, &processingBuffer, 1, vDSP_Length(sampleCount))
    
    // That is imagined to do what I am doing under - utilizing a sliding window to seek out maximums, but it surely was producing unusual outcomes
    // vDSP_vswmax(processingBuffer, samplePrecision, &maxSamplesBuffer, 1, newSampleCount, vDSP_Length(samplePrecision))
    
    // As a substitute, we use a for loop with a stride of size samplePrecision to specify a spread of samples
    // This vary is handed to our personal maximumIn() technique
    
    var maxSamplesBuffer = [Float](repeating: 0.0,
                                   rely: reducedSampleCount)
    
    var offset = 0
    
    for i in stride(from: 0, to: sampleCount-samplesPerPixel, by: samplesPerPixel) {
        maxSamplesBuffer[offset] = maximumIn(processingBuffer, from: i, to: i+samplesPerPixel)
        offset = offset + 1
    }
    
    // Convert the maxSamplesBuffer values to CGPoints for drawing
    // We additionally normalize them for show right here
    readFile.leftPoints = maxSamplesBuffer.enumerated().map({ (index, worth) -> CGPoint in
        let normalized = normalizeForDisplay(worth)
        let level = CGPoint(x: CGFloat(index), y: CGFloat(normalized))
        return level
    })
    
    // Interpolate factors for smoother drawing
    for (index, level) in readFile.leftPoints.enumerated() {
        if index > 0 {
            let interpolatedPoint = CGPoint.lerp(begin: readFile.leftPoints[index - 1], finish: level, t: 0.5)
            readFile.leftPoints[index] = interpolatedPoint
        }
    }
}

func drawDetailedWaveform(_ rect: CGRect) {
    let path = UIBezierPath()
    
    path.transfer(to: CGPoint(x: 0.0, y: rect.top/2))
    
    // left channel
    
    for level in readFile.leftPoints {
        let drawFrom = CGPoint(x: level.x, y: path.currentPoint.y)
        
        path.transfer(to: drawFrom)
        
        // backside half
        let drawPointBottom = CGPoint(x: level.x, y: path.currentPoint.y + (level.y))
        path.addLine(to: drawPointBottom)
        
        path.shut()
        
        // high half
        let drawPointTop = CGPoint(x: level.x, y: path.currentPoint.y - (level.y))
        path.addLine(to: drawPointTop)
        
        path.shut()
    }
    
    UIColor.orange.set()
    path.stroke()
    path.fill()
}

func drawSoundcloudWaveform(_ rect: CGRect) {
    let path = UIBezierPath()
    
    path.transfer(to: CGPoint(x: 0.0, y: rect.top/2))
    
    // left channel
    
    var index = 0
    
    whereas index < readFile.leftPoints.rely {
        let level = readFile.leftPoints[index]
        
        let drawFrom = CGPoint(x: level.x, y: path.currentPoint.y)
        
        // backside half
        path.transfer(to: drawFrom)
        
        let drawPointBottom = CGPoint(x: level.x, y: path.currentPoint.y + (level.y))
        path.addLine(to: drawPointBottom)
        path.addLine(to: CGPoint(x: drawPointBottom.x + pixelWidth, y: drawPointBottom.y))
        path.addLine(to: CGPoint(x: drawFrom.x + pixelWidth, y: drawFrom.y))
        
        path.shut()
        
        // high half
        path.transfer(to: drawFrom)
        
        let drawPointTop = CGPoint(x: level.x, y: path.currentPoint.y - (level.y))
        path.addLine(to: drawPointTop)
        path.addLine(to: CGPoint(x: drawPointTop.x + pixelWidth, y: drawPointTop.y))
        path.addLine(to: CGPoint(x: drawFrom.x + pixelWidth, y: drawFrom.y))
        
        path.shut()
        
        // increment index
        index = index + Int(pixelWidth) + Int(pixelSpacing)
    }
    
    UIColor(purple:0.21, inexperienced:0.77, blue:0.78, alpha:1.0).set()
    path.stroke()
    path.fill()
}

override public func draw(_ rect: CGRect) {
    makePoints()
    
    // this clears the rect
    backgroundColor = .black
    
    change fashion {
    case .soundcloud:
        drawSoundcloudWaveform(rect)
         }
        }
     }

   public extension UIView {
   func normalizeForDisplay(_ worth: Float) -> Float {
    let maxHeight = Float(bounds.top)
    let minHeight = Float(maxHeight / 2.0)
    let normalized = worth * minHeight
    return normalized
     }
   }

Utilization instance:

waveform.backgroundColor = UIColor(hexString: "F4F4F4")
waveform.openFile(URL(string: SongUrl)!)

[ad_2]

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments