how to monitor audio input on ios using swift - example?

只谈情不闲聊 提交于 2019-12-21 20:29:00

问题


I want to write a simple app that 'does something' when the sound level at the mic reaches a certain level, showing the audio input levels for extra credit

cant find any examples in swift that get to this -- dont want to record, just monitor

have been checking out the docs on the AVFoundation classes but cant get off the ground

thanks


回答1:


Let you can use below code :

func initalizeRecorder ()
 {
    do {

        try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayAndRecord)
        try AVAudioSession.sharedInstance().setActive(true)

    }catch{
        print(error);
    }


    let stringDir:NSString = self.getDocumentsDirectory();
    let audioFilename = stringDir.stringByAppendingPathComponent("recording.m4a")
    let audioURL = NSURL(fileURLWithPath: audioFilename)
    print("File Path : \(audioFilename)");

    // make a dictionary to hold the recording settings so we can instantiate our AVAudioRecorder

    let settings = [
        AVFormatIDKey: Int(kAudioFormatMPEG4AAC),
        AVSampleRateKey: 12000.0,
        AVNumberOfChannelsKey: 1 as NSNumber,
        AVEncoderBitRateKey:12800 as NSNumber,
        AVLinearPCMBitDepthKey:16 as NSNumber,
        AVEncoderAudioQualityKey: AVAudioQuality.High.rawValue
    ]



do {
        if audioRecorder == nil
        {
            audioRecorder = try AVAudioRecorder(URL: audioURL, settings: settings )
            audioRecorder!.delegate = self
            audioRecorder!.prepareToRecord();
            audioRecorder!.meteringEnabled = true;
        }
        audioRecorder!.recordForDuration(NSTimeInterval(5.0));
     } catch {
        print("Error")
    }

 }

//GET DOCUMENT DIR PATH
 func getDocumentsDirectory() -> String {
    let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
    let documentsDirectory = paths[0]
    return documentsDirectory
}
////START RECORDING
@IBAction func btnStartPress(sender: AnyObject) {

    recordingSession = AVAudioSession.sharedInstance()
    do {


        recordingSession.requestRecordPermission() { [unowned self] (allowed: Bool) -> Void in
            dispatch_async(dispatch_get_main_queue()) {
                if allowed {
                 print("Allowd Permission Record!!")
                    self.initalizeRecorder ()
                    self.audioRecorder!.record()

                    //instantiate a timer to be called with whatever frequency we want to grab metering values
                    self.levelTimer = NSTimer.scheduledTimerWithTimeInterval(0.02, target: self, selector: Selector("levelTimerCallback"), userInfo: nil, repeats: true)

                } else {
                    // failed to record!
                    self.showPermissionAlert();
                    print("Failed Permission Record!!")
                }
            }
        }
    } catch {
        // failed to record!
        print("Failed Permission Record!!")
    }

}


    //This selector/function is called every time our timer (levelTime) fires
func levelTimerCallback() {
    //we have to update meters before we can get the metering values
    if audioRecorder != nil
    {
        audioRecorder!.updateMeters()

        let ALPHA : Double = 0.05;
        let peakPowerForChannel : Double = pow(Double(10.0), (0.05) * Double(audioRecorder!.peakPowerForChannel(0)));
        lowPassResults = ALPHA * peakPowerForChannel + Double((1.0) - ALPHA) * lowPassResults;
        print("low pass res = \(lowPassResults)");
        if (lowPassResults > 0.7 ){
           print("Mic blow detected");
           }
       }


 }
     //STOP RECORDING
    @IBAction func btnStopPress(sender: AnyObject) {

            if audioRecorder != nil
            {
                audioRecorder!.stop()
                self.levelTimer.invalidate()
            }

        }



回答2:


In AVAudioRecorder you can "record audio" (you don't have to save it) and set meteringEnabled to use the function peakPowerForChannel(_:)

It will

Returns the peak power for a given channel, in decibels, for the sound being recorded.

This link may provide a sample code.

Let me know if it help you.



来源:https://stackoverflow.com/questions/35929989/how-to-monitor-audio-input-on-ios-using-swift-example

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!