[swift] 시각적으로 사운드 파형 표시하기

사운드 파형은 오디오 신호의 시간 및 주파수 도메인 특성을 시각적으로 표현하는 도구입니다. Swift를 사용하여 사운드 파형을 표시하는 방법을 알아보겠습니다.

AVAudioPlayer 사용하기

AVAudioPlayer는 iOS와 macOS에서 오디오 파일을 재생하기 위한 기본 클래스입니다. 이를 사용하여 사운드 파일에서 오디오 데이터를 읽고 파형을 그릴 수 있습니다.

import AVFoundation
import UIKit

class WaveformView: UIView {
    private var waveformSamples: [CGFloat] = []
    
    override func draw(_ rect: CGRect) {
        guard let context = UIGraphicsGetCurrentContext() else { return }
        
        context.setFillColor(UIColor.white.cgColor)
        context.setStrokeColor(UIColor.red.cgColor)
        
        for (index, sample) in waveformSamples.enumerated() {
            let x = rect.width * CGFloat(index) / CGFloat(waveformSamples.count)
            let y = rect.height / 2 - rect.height * sample / 2
            
            if index == 0 {
                context.move(to: CGPoint(x: x, y: y))
            } else {
                context.addLine(to: CGPoint(x: x, y: y))
            }
        }
        
        context.strokePath()
    }
    
    func loadSound(fileURL: URL) {
        do {
            let soundData = try Data(contentsOf: fileURL)
            
            guard let audioPlayer = try? AVAudioPlayer(data: soundData) else { return }
            
            audioPlayer.prepareToPlay()
            audioPlayer.play()
            
            waveformSamples = audioPlayer.samples
            setNeedsDisplay()
        } catch {
            print("Error loading sound file: \(error.localizedDescription)")
        }
    }
}

위의 코드는 WaveformView라는 커스텀 UIView 서브클래스를 정의하고, draw(_:) 메서드를 사용하여 파형을 그리는 데 필요한 로직을 구현합니다. loadSound(fileURL:) 메서드는 사운드 파일을 로드하고, wavefomSamples 배열에 오디오 데이터의 샘플 값을 저장합니다.

사용 방법은 다음과 같습니다:

let waveformView = WaveformView(frame: CGRect(x: 0, y: 0, width: 320, height: 200))
waveformView.loadSound(fileURL: soundFileURL)

사운드 파형을 표시하려는 뷰를 만들고, loadSound(fileURL:) 메서드를 호출하여 사운드 파일을 로드하면 파형이 그려집니다.

참고 자료