'How to create a noise level meter swift?

I am trying to make a noise level meter, but I am running into some errors such as it keeps returning 0 even though I am being quiet. Can someone please assist me in fixing these issues and post some code? Here is my code and thanks in advance!:

//
//  ViewController.swift
//  audiometer
//
//  Created by Vaibhav Satishkumar on 4/17/22.
//

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioRecorderDelegate {
    
    
    var mic = AVAudioRecorder()
    
    let captureSession = AVCaptureSession()

    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        mic.isMeteringEnabled = true
        
        let volume = mic.peakPower(forChannel: 0)
     
        mic.updateMeters()
        // Find the default audio device.
        guard let audioDevice = AVCaptureDevice.default(for: .audio) else { return }

        do {
            // Wrap the audio device in a capture device input.
            let audioInput = try AVCaptureDeviceInput(device: audioDevice)
            // If the input can be added, add it to the session.
            if captureSession.canAddInput(audioInput) {
                captureSession.addInput(audioInput)
            }
        } catch {
            // Configuration failed. Handle error.
        }
        captureSession.startRunning()
        while asdasdasd == 0{
        
            mic.updateMeters()
        print(volume)
        }
        // Do any additional setup after loading the view.
    }

    
    
var asdasdasd = 0
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source