我需要计算用麦克风录制的声音的频率,单位是赫兹。我现在正在做的是使用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()
}
}我不知道如何得到声音的频率,单位是赫兹。对于我来说,使用第三方框架也很好。
谢谢。
发布于 2020-12-02 03:38:26
任何给定的录制声音都不会有单一的频率。它将有不同振幅的混合频率。
您需要对输入声音进行频率分析,通常使用FFT (快速傅立叶变换)对音频数据进行分析。
谷歌搜索显示了这篇关于使用加速框架进行频率分析的文章:
http://www.myuiviews.com/2016/03/04/visualizing-audio-frequency-spectrum-on-ios-via-accelerate-vdsp-fast-fourier-transform.html
https://stackoverflow.com/questions/65096708
复制相似问题