【问题标题】:how to monitor audio input on ios using swift - example?如何使用 swift 监控 ios 上的音频输入 - 示例?
【发布时间】:2016-03-11 00:22:15
【问题描述】:

我想编写一个简单的应用程序,当麦克风的声音级别达到一定级别时“做某事”,显示音频输入级别以获得额外奖励

在 swift 中找不到任何涉及到这一点的示例——不想记录,只是监视

一直在查看有关 AVFoundation 课程的文档,但无法启动

谢谢

【问题讨论】:

    标签: ios swift avfoundation


    【解决方案1】:

    让你可以使用下面的代码:

    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()
                }
    
            }
    

    【讨论】:

    • 在哪里声明 lowPassResults 变量?
    • @RaviSharma ,你可以在类的顶部声明lowPassResults。
    【解决方案2】:

    AVAudioRecorder你可以“录制音频”(你不必保存它)并设置meteringEnabled使用peakPowerForChannel(_:)功能

    会的

    返回给定通道的峰值功率,以分贝为单位,用于录制的声音。

    This link may provide a sample code.

    如果对你有帮助,请告诉我。

    【讨论】:

    • 它仍然会写入文件。
    猜你喜欢
    • 2021-05-25
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多