Chapters

Hide chapters

SwiftUI Cookbook

Live Edition · iOS 16.4 · Swift 5.8.1 · Xcode 14.3.1

Creating Animated Visualizations for Audio & Video in SwiftUI
Written by Team Kodeco

Have you ever wanted to add some pizzazz to your audio and video app? Adding animated visualizations to your app can provide a cool and immersive experience for your users.

In SwiftUI, creating animated visualizations for audio and video is a breeze. All you need is a basic understanding of the Path and Shape protocols.

struct AnimatedVisualizer: Shape {
  let audioSamples: [CGFloat]

  func path(in rect: CGRect) -> Path {
    var path = Path()

    let height = rect.height
    let width = rect.width / CGFloat(audioSamples.count)

    for i in 0 ..< audioSamples.count {
      let x = width * CGFloat(i)
      let y = CGFloat(audioSamples[i]) * height

      path.addRect(CGRect(x: x, y: 0, width: width, height: y))
    }

    return path
  }
}

struct ContentView: View {
  @State private var audioSamples: [CGFloat] = [0.2, 0.5, 0.8, 0.3, 0.6, 0.9, 0.4, 0.4, 0.4, 0.4]

  var body: some View {
    ZStack {
      AnimatedVisualizer(audioSamples: audioSamples)
        .fill(Color.red)
        .opacity(0.8)
        .animation(Animation.easeInOut(duration: 0.2).repeatForever(autoreverses: true), value: audioSamples)
        .frame(maxWidth: .infinity, maxHeight: .infinity)
    }
    .onAppear {
      Timer.scheduledTimer(withTimeInterval: 0.2, repeats: true) { timer in
        self.audioSamples = self.generateAudioSamples()
      }
    }
  }

  func generateAudioSamples() -> [CGFloat] {
    var samples: [CGFloat] = []
    for _ in 0...10 {
      samples.append(CGFloat.random(in: 0...1))
    }
    return samples
  }
}

Your preview should look like this:

Create an animated visualizer with audio metadata.
Create an animated visualizer with audio metadata.

In this example code, you have created a custom shape called AnimatedVisualizer. The shape takes in an array of CGFloat values representing the audio samples. The path function is then used to create a visualization based on the provided audio samples.

You then use this custom shape in your ContentView, where you use a ZStack to add your visualization as a background element. You also add some animations to give the visualization a cool pulsating effect.

In the onAppear block, you generate random audio samples every 0.2 seconds to update the visualization dynamically.

With this code example, you should be able to create your own animated visualizations for your audio and video app in no time.

Have a technical question? Want to report a bug? You can ask questions and report bugs to the book authors in our official book forum here.
© 2024 Kodeco Inc.