2

I am using the AVAudioRecorder to record some sound from the mic. I am using [recorder recordForDuration: 10] I want to upload the sound file when 10 second is over. Is there a way to specify this ? Any help will be appreciated.

Thanks.

- ahsan

Ahsan
  • 2,964
  • 11
  • 53
  • 96

4 Answers4

3

You can use the delegate audioRecorderDidFinishRecording:successfully: only if you send a double, float or NSTimeInterval as the duration of the recording.

These will trigger the delegate

[recorder recordForDuration:10.0]; // double
[recorder recordForDuration:10.0f]; // float

This will not trigger the delegate

[recorder recordForDuration:10]; // int

Technically, these should be of the type NSTimeInterval and not float or double.

Source: @Johnmph comment

Ross
  • 14,266
  • 12
  • 60
  • 91
  • Why downvote my answer and copy it with my comment to make a new answer ?? – Johnmph Oct 02 '12 at 15:46
  • 1
    What is really unhelpful, it is to copy / paste an answer a year later and to down vote this answer. – Johnmph Oct 02 '12 at 16:29
  • I don't need credit or source but i just don't like that you down voted my answer. What is wrong in my answer ? Don't you need a delegate to be notified when the recording is done ? Ok for saying that my answer is not complete for this case and to let a new more complete answer but not for down voting my answer. Down vote an answer if it is wrong not if it is not complete. – Johnmph Oct 02 '12 at 17:02
  • I didn't learn anything from your fight, i tested all of your cases, and none of them is triggering the audioRecorderDidFinishRecording:successfully: – Monicka Jul 12 '15 at 18:55
3

Another way will be to use a Timer function ! :)

Xcode Objective-C | iOS: delay function / NSTimer help?

Community
  • 1
  • 1
Ahsan
  • 2,964
  • 11
  • 53
  • 96
1

You need to set the delegate of the AVAudioRecorder object.

The delegate will receive the message audioRecorderDidFinishRecording:successfully: when the recording is done.

See documentation of AVAudioRecorder :

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioRecorder_ClassReference/Reference/Reference.html%23//apple_ref/occ/cl/AVAudioRecorder

and AVAudioRecorderDelegate :

http://developer.apple.com/library/ios/#documentation/AVFoundation/Reference/AVAudioRecorderDelegate_ProtocolReference/Reference/Reference.html%23//apple_ref/occ/intf/AVAudioRecorderDelegate

Johnmph
  • 3,391
  • 24
  • 32
  • This is what I did, added - (void)audioRecorderDidFinishRecording:(AVAudioRecorder *)recorder successfully:(BOOL)flag {NSLog (@"Done");} .. however I dont get any output :(.. any help ? (I also added [self.recorder.delegate self]; ) – Ahsan May 29 '11 at 23:22
  • none of the following works !! recorder.delegate=self; or [recorder setDelegate:self]; – Ahsan May 30 '11 at 03:39
  • the delegate functions work only if I explicitly use [recorder stop]...not if I use [recorder recordForDuration: 10] ..any help ? – Ahsan May 30 '11 at 04:26
  • 2
    @Ahsan, recordForDuration requires a NSTimeInterval (which is a double value) and you pass an int value, maybe that's the problem. If that doesn't work also, you can use record instead recordForTime and immediatly after create a nstimer which will call stop method after time of your choice – Johnmph May 30 '11 at 10:04
0

Swift code for recording for 10 seconds:

    var audioRecorder: AVAudioRecorder! 
    var meterTimer: NSTimer?

    func btnRecordAction(sender: UIButton) {

    let currentDateTime = NSDate()
    let formatter = NSDateFormatter()
    formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    let recordingName = formatter.stringFromDate(currentDateTime)+".m4a"
    let filePath = self.docPath!.stringByAppendingPathComponent(recordingName)

    var error: NSError?
    var session = AVAudioSession.sharedInstance()
    session.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .DuckOthers, error: &error)

    let recordSettings = [
        AVFormatIDKey: kAudioFormatMPEG4AAC,
        AVEncoderAudioQualityKey : AVAudioQuality.Max.rawValue,
        AVNumberOfChannelsKey: 1,
        AVSampleRateKey : 44100.0 
    ]

    let url = NSURL(fileURLWithPath: filePath)
    self.audioRecorder = AVAudioRecorder(URL: url, settings: recordSettings as! [NSObject : AnyObject] , error: &error)
    if let e = error {
        println("AVAudioRecorder error = \(e.localizedDescription)" )
    } else {
        self.audioRecorder.delegate = self
        self.audioRecorder.meteringEnabled = true
        self.audioRecorder.recordForDuration(10.0)
        self.audioRecorder.prepareToRecord()
        self.audioRecorder.record()

        if self.audioRecorder.recording == true {
            self.meterTimer = NSTimer.scheduledTimerWithTimeInterval(0.1,
                target:self,
                selector:"updateAudioMeter:",
                userInfo:nil,
                repeats:true)
        }
    }
}

func audioRecorderDidFinishRecording(recorder: AVAudioRecorder!, successfully flag: Bool) {
        println("finished recording \(flag)")


        // ios8 and later
        var alert = UIAlertController(title: "Recorder",
            message: "Finished Recording",
            preferredStyle: .Alert)
        alert.addAction(UIAlertAction(title: "Keep", style: .Default, handler: {action in
            println("keep was tapped")
        }))
        alert.addAction(UIAlertAction(title: "Delete", style: .Default, handler: {action in
            self.audioRecorder?.deleteRecording()
        }))
        self.presentViewController(alert, animated:true, completion:nil)
}

func audioRecorderEncodeErrorDidOccur(recorder: AVAudioRecorder!,
    error: NSError!) {
        println("\(error.localizedDescription)")
}

func updateAudioMeter(timer:NSTimer) {

    if  self.audioRecorder.recording {
        let dFormat = "%02d"
        let min:Int = Int(self.audioRecorder.currentTime / 60)
        let sec:Int = Int(self.audioRecorder.currentTime % 60)
        let s = "Recording: \(String(format: dFormat, min)):\(String(format: dFormat, sec)) secs"
        self.lblRecorderTime!.text = s
        self.audioRecorder.updateMeters()

    }

}
Thiru
  • 1,380
  • 13
  • 21