user4034967
user4034967

Reputation:

Swift - LongPress Gesture on Button to record Audio with AVFoundation

I'm trying to implement a record button for my chat, which records as long as you hold the button. I implemented a longpressGestureRecognizer, but unfortunately it only records for one second, no matter how long I press.

Here is the code:

let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(longPress(_:)))
    longPressGestureRecognizer.minimumPressDuration = 1


    self.recordingSession = AVAudioSession.sharedInstance()

    do {
        try self.recordingSession.setCategory(AVAudioSessionCategoryPlayAndRecord)
        try self.recordingSession.setActive(true)
        self.recordingSession.requestRecordPermission() { [unowned self] allowed in
            DispatchQueue.main.async {
                if allowed {
                    self.record_button.addGestureRecognizer(longPressGestureRecognizer)
                } else {
                    // failed to record!
                }
            }
        }
    } catch {
        // failed to record!
    }

// Gesture Recognizer for the Record Button, so as long as it is pressed, record!
func longPress(_ longPressGestureRecognizer: UILongPressGestureRecognizer){
    if longPressGestureRecognizer.state == .ended {
        print("long press ended")
        let recordImage = UIImage(named: "ic_mic_white")
        record_button.setImage(recordImage, for: .normal)
        self.recordTapRelease()
    }
    if longPressGestureRecognizer.state == .began {
        let recordingTapImage = UIImage(named: "ic_mic_none_white")
        record_button.setImage(recordingTapImage, for: .normal)
        self.recording()

    }
}

EDIT I implemented the .touchdown .touchupinside events etc. I still get the same behaviour, unless I slight up above the record button leaving the orange view. Then the recording image button image also changes, showing recording, and if I release and move further up it stops recording.

Recording button function

Upvotes: 1

Views: 2587

Answers (1)

Ahmad F
Ahmad F

Reputation: 31665

You don't even have to create UILongPressGestureRecognizer for achieving this; You can do it by implementing touchDown, touchUpInside and touchDragExit events for a UIButton.

At the first look, it might seems that it's more complicated than working with UILongPressGestureRecognizer, but I think that it is more logical and even more readable.

Follow the steps in this answer and hopefully you will get the desired behavior for your recording button. It also has another answer if you insist to use UILongPressGestureRecognizer.

Hope this helped.

Upvotes: 1

Related Questions