首页 > 解决方案 > 获取带麦克风的录音机的频率

问题描述

我需要计算用麦克风录制的声音的频率(以赫兹为单位)。我现在正在做的是用AVAudioRecorder一个定时器来听麦克风,每 0.5 秒调用一个特定的函数。这里有一些代码:


class ViewController: UIViewController {
    
    var audioRecorder: AVAudioRecorder?
    var timer: Timer?

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        
        let permission = AVAudioSession.sharedInstance().recordPermission
        
        if permission == AVAudioSession.RecordPermission.undetermined {
            
            AVAudioSession.sharedInstance().requestRecordPermission { (granted) in
                if granted {
                    print("Permission granted!")
                } else {
                    print("Permission not granted!")
                }
            }
        } else if permission == AVAudioSession.RecordPermission.granted {
            
            do {
                try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.record)
                
                let settings = [
                    AVSampleRateKey: 44100.0,
                    AVFormatIDKey: kAudioFormatAppleLossless,
                    AVNumberOfChannelsKey: 1,
                    AVEncoderAudioQualityKey: AVAudioQuality.max
                ] as [String : Any]
                
                audioRecorder = try AVAudioRecorder.init(url: NSURL.fileURL(withPath: "dev/null"), settings: settings)
                audioRecorder?.prepareToRecord()
                audioRecorder?.isMeteringEnabled = true
                audioRecorder?.record()
                
                timer = Timer.scheduledTimer(
                    timeInterval: 0.5,
                    target: self,
                    selector: #selector(analyze),
                    userInfo: nil,
                    repeats: true
                )
            } catch (let error) {
                print("Error! \(error.localizedDescription)")
            }
        }
    }


    @objc func analyze() {
        
        audioRecorder?.updateMeters()
        
        let peak = audioRecorder?.peakPower(forChannel: 0)
        
        print("Peak : \(peak)")
        
        audioRecorder?.updateMeters()
    }
}

我不知道如何以赫兹为单位获得声音的频率。对我来说使用 3rd 方框架也很好。

谢谢。

标签: iosswiftaudioavkit

解决方案


任何给定的录制声音都不会有单一频率。它将具有不同幅度的频率混合。

您需要对输入声音进行频率分析,通常对音频数据使用 FFT(快速傅立叶变换)。

谷歌搜索显示了这篇关于使用 Accelerate 框架进行频率分析的文章:

http://www.myuiviews.com/2016/03/04/visualizing-audio-frequency-spectrum-on-ios-via-accelerate-vdsp-fast-fourier-transform.html


推荐阅读