This is my swiftUI code to create a recording view and save the audio file. I'm not happy with the equalizer effect. Change the effect as follow:
A repetitive bars will be shown on the screen horizontally and each sample will get the current value of the audio level. The old bars should move out to the left and disappear. The maximum number of bar should be 20. The new bars with the current audio levels should be added from right side.
code
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
//
// ContentView.swift
// TestVoiceRecording
//
// Created by ark on 08.07.24.
//
import SwiftUI
import CoreData
import SwiftUI
import AVFoundation
// MARK: - Audio Recorder Model (using Facade pattern for simplified access)
class AudioRecorder: ObservableObject {
private var audioRecorder: AVAudioRecorder?
private var timer: Timer?
@Published var isRecording: Bool = false
@Published var audioLevels: [Float] = Array(repeating: 0.0, count: 50) // For equalizer effect
// Error handling
enum AudioRecorderError: Error {
case initializationFailed
case recordingFailed
case permissionsDenied
}
func requestPermissions(completion: @escaping (Result<Bool, AudioRecorderError>) -> Void) {
AVAudioSession.sharedInstance().requestRecordPermission { granted in
DispatchQueue.main.async { // Ensure UI updates happen on the main thread
completion(granted ? .success(true) : .failure(.permissionsDenied))
}
}
}
func startRecording() throws {
// 1. Request Microphone Access
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playAndRecord, mode: .default)
try audioSession.setActive(true)
// 2. Set up the file path for recording
let documentsURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let fileName = "recording.m4a" // Adjust file type as needed
let fileURL = documentsURL.appendingPathComponent(fileName)
// 3. Define the recording settings
let settings: [String: Any] = [
AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
AVSampleRateKey: 16000.0,
AVNumberOfChannelsKey: 1,
AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
]
// 4. Initialize and prepare the recorder
do {
audioRecorder = try AVAudioRecorder(url: fileURL, settings: settings)
audioRecorder?.isMeteringEnabled = true // Enable level metering for the equalizer
audioRecorder?.prepareToRecord()
audioRecorder?.record()
isRecording = true
// Start timer to update audio levels
timer = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { timer in
self.updateAudioLevels()
}
} catch {
// Handle recording initialization errors here
isRecording = false
throw AudioRecorderError.initializationFailed // Propagate error
}
}
func stopRecording() {
audioRecorder?.stop()
audioRecorder = nil
isRecording = false
timer?.invalidate()
timer = nil
}
private func updateAudioLevels() {
guard let recorder = audioRecorder, recorder.isRecording else { return }
recorder.updateMeters()
var levels: [Float] = []
let channels = recorder.format.channelCount
let avgPower = recorder.averagePower(forChannel: 0)
let linearLevel = pow(10.0, avgPower / 20.0) // Convert to linear scale
levels.append(linearLevel)
DispatchQueue.main.async {
self.audioLevels = levels
}
}
}
// MARK: - Equalizer View
struct EqualizerBarView: View {
var value: Float
var body: some View {
RoundedRectangle(cornerRadius: 5)
.fill(LinearGradient(gradient: Gradient(colors: [.green, .yellow, .red]), startPoint: .bottom, endPoint: .top))
.frame(width: 10, height: CGFloat(value * 100)) // Adjust scaling as needed
}
}
struct EqualizerView: View {
@ObservedObject var audioRecorder: AudioRecorder
var body: some View {
HStack(spacing: 16) {
ForEach(0..<audioRecorder.audioLevels.count, id: \.self) { index in
EqualizerBarView(value: audioRecorder.audioLevels[index])
}
}
.padding()
}
}
// MARK: - Main View
struct ContentView: View {
@StateObject private var audioRecorder = AudioRecorder()
@State private var showingAlert = false
var body: some View {
VStack {
// ... Your other view content
EqualizerView(audioRecorder: audioRecorder)
HStack {
Button(action: {
if audioRecorder.isRecording {
audioRecorder.stopRecording()
} else {
do {
try audioRecorder.startRecording()
} catch AudioRecorder.AudioRecorderError.permissionsDenied {
showingAlert = true
} catch {
// Handle other errors
print("Recording failed")
}
}
}) {
Text(audioRecorder.isRecording ? "Stop Recording" : "Start Recording")
}
.padding()
// ... Your other button
}
}
.alert("Microphone Access Denied", isPresented: $showingAlert) {
Button("OK", role: .cancel) { }
} message: {
Text("Please enable microphone access in Settings to record audio.")
}
.onAppear {
audioRecorder.requestPermissions { result in
// Handle permission request result (e.g., show an alert if denied)
}
}
}
}
#Preview {
ContentView().environment(\.managedObjectContext, PersistenceController.preview.container.viewContext)
}
To implement the effect you described, we'll need to modify the AudioRecorder class and create a new EqualizerView. Here's the updated code:
swift
import SwiftUI
import AVFoundation
class AudioRecorder: ObservableObject {
private var audioRecorder: AVAudioRecorder?
private var timer: Timer?
@Published var isRecording: Bool = false
@Published var audioLevels: [Float] = []
// ... (keep the rest of the AudioRecorder class as is)
private func updateAudioLevels() {
guard let recorder = audioRecorder, recorder.isRecording else { return }
recorder.updateMeters()
let avgPower = recorder.averagePower(forChannel: 0)
let linearLevel = pow(10.0, avgPower / 20.0) // Convert to linear scale
DispatchQueue.main.async {
self.audioLevels.append(linearLevel)
if self.audioLevels.count > 20 {
self.audioLevels.removeFirst()
}
}
}
}
struct EqualizerBarView: View {
var value: Float
var body: some View {
RoundedRectangle(cornerRadius: 5)
.fill(LinearGradient(gradient: Gradient(colors: [.green, .yellow, .red]), startPoint: .bottom, endPoint: .top))
.frame(width: 10, height: CGFloat(value * 100))
}
}
struct EqualizerView: View {
@ObservedObject var audioRecorder: AudioRecorder
var body: some View {
HStack(spacing: 2) {
ForEach(audioRecorder.audioLevels.indices, id: \.self) { index in
EqualizerBarView(value: audioRecorder.audioLevels[index])
}
}
.frame(width: 220, alignment: .trailing) // Adjust width as needed
.animation(.linear, value: audioRecorder.audioLevels)
}
}
struct ContentView: View {
@StateObject private var audioRecorder = AudioRecorder()
@State private var showingAlert = false
var body: some View {
VStack {
EqualizerView(audioRecorder: audioRecorder)
HStack {
Button(action: {
if audioRecorder.isRecording {
audioRecorder.stopRecording()
} else {
do {
try audioRecorder.startRecording()
} catch AudioRecorder.AudioRecorderError.permissionsDenied {
showingAlert = true
} catch {
print("Recording failed")
}
}
}) {
Text(audioRecorder.isRecording ? "Stop Recording" : "Start Recording")
}
.padding()
}
}
.alert("Microphone Access Denied", isPresented: $showingAlert) {
Button("OK", role: .cancel) { }
} message: {
Text("Please enable microphone access in Settings to record audio.")
}
.onAppear {
audioRecorder.requestPermissions { result in
// Handle permission request result
}
}
}
}
Here's what changed:
In the AudioRecorder class, we modified the audioLevels array to be an empty array initially.
In the updateAudioLevels() method, we now append new levels to the audioLevels array and remove the oldest one if the count exceeds 20.
The EqualizerView has been updated to display bars horizontally, with new bars added from the right and old bars moving to the left.
We added an animation to the EqualizerView to make the movement of bars smooth.
The EqualizerView is now constrained to a fixed width (220 points in this example, but you can adjust it) and aligned to the trailing edge to ensure that new bars always appear from the right.
This implementation will create the effect you described: new bars will appear from the right side, pushing older bars to the left, with a maximum of 20 bars visible at any time. The bars will represent the current audio levels, updating in real-time as you record.