Skip to content

Instantly share code, notes, and snippets.

@Inncoder
Last active March 20, 2021 15:49
Show Gist options
  • Select an option

  • Save Inncoder/c24c8d1aeb59b5ac393ce50db2469bc4 to your computer and use it in GitHub Desktop.

Select an option

Save Inncoder/c24c8d1aeb59b5ac393ce50db2469bc4 to your computer and use it in GitHub Desktop.
Sound Visualizer
//
// SoundVisualizer.swift
// Animations
//
// Created by Inncoder on 21/09/2020.
// Copyright © 2020 Inncoder AS. All rights reserved.
//
import SwiftUI
struct Bar: Identifiable, Hashable {
var id: Int
var height: CGFloat
}
class BarManager: ObservableObject {
@Published var bars: [Bar] = []
}
struct SoundVisualizer: View {
@ObservedObject var barManager = BarManager()
var body: some View {
ZStack {
Circle()
.frame(width: circleSize, height: circleSize)
.foregroundColor(circleColor)
HStack {
ForEach(1..<(barManager.bars.count + 1)) { i in
ZStack {
LinearGradient(gradient: Gradient(colors: [topColor, bottomColor]), startPoint: .top, endPoint: .bottom)
.frame(width: barWidth, height: barMaxHeight)
.mask(
ZStack {
Capsule()
.frame(width: barWidth, height: barManager.bars[i - 1].height)
}
.frame(height: barMaxHeight, alignment: .bottom)
)
}
}
}
}
.onAppear {
startAnimation()
}
}
init() {
for i in 0..<4 {
barManager.bars.append(Bar(id: i, height: barMinHeight))
}
}
// MARK: - Drawing constants
let topColor: Color = Color(red: 0.51, green: 0.20, blue: 0.69)
let bottomColor: Color = Color(red: 0.32, green: 0.36, blue: 0.83)
let circleColor: Color = Color(red: 0.189, green: 0.187, blue: 0.256)
let circleSize: CGFloat = 200
let barMaxHeight: CGFloat = 100
let barMinHeight: CGFloat = 50
let barWidth: CGFloat = 20
let loopTime: Double = 1.5
// MARK: - Functions
func startAnimation() {
for i in 1..<(barManager.bars.count + 1) {
let speedUp = (loopTime / 3) / Double(i)
let speedDown = speedUp * 3
Timer.scheduledTimer(withTimeInterval: speedUp + speedDown, repeats: true) { _ in
withAnimation(Animation.linear(duration: speedUp)) {
barManager.bars[i - 1].height = barMaxHeight
}
DispatchQueue.main.asyncAfter(deadline: .now() + speedUp) {
withAnimation(Animation.linear(duration: speedDown)) {
barManager.bars[i - 1].height = barMinHeight
}
}
}
}
}
}
struct SoundVisualizer_Previews: PreviewProvider {
static var previews: some View {
SoundVisualizer()
}
}
@mhassantahir

Copy link
Copy Markdown

I have a question, Are we want any kind of .xml code for it or not.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment