简体   繁体   English

Swift - Sample - 如何在使用 AVAudioRecorder 录制前后播放哔声?

[英]Swift - Sample - How to play beep sound before and after recording using AVAudioRecorder?

I want to implement similar record button like Whatsapp in iOS using Swift, where when user holds the button down, a beep sound indicates start, after which recording starts and when user releases the button, recording stops and another beep sound indicates recording finished.我想在 iOS 中使用 Swift 实现类似 Whatsapp 的类似录制按钮,当用户按住按钮时,发出哔声表示开始,之后录制开始,当用户释放按钮时,录制停止,另一声提示音表示录制完成。

I tried implementing this feature using the following code:我尝试使用以下代码实现此功能:

func startRecording(sender: UIDataButton?, callData: NSDictionary?) -> Bool {
    do {
        if (self.audioRecorder == nil) {

            AudioServicesPlayAlertSound(1110) // JBL_Begin

            self.audioSession = AVAudioSession.sharedInstance()
            try self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .MixWithOthers)
            try self.audioSession.setMode(AVAudioSessionModeVoiceChat)
            try self.audioSession.setActive(true)

            if (sender != nil) {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    sender!.setTitle("Recording...", forState: .Normal)
                })
            }

            try self.audioRecorder = AVDataAudioRecorder(URL: self.fileURL("\(CurrentTimestamp)_aud.mp4")!,
                settings: self.recordSettings)

            if (sender != nil) {
                self.audioRecorder.setRecorderSender(sender!)
            }
            if (callData != nil) {
                self.audioRecorder.setRecorderData(callData!)
            }

            self.audioRecorder.delegate = self

            if (self.audioRecorder.prepareToRecord()) {
                if (self.audioRecorder.record()) {
                    NSLog("audioRecorder started recording")
                    return true
                } else {
                    self.audioRecorder = nil
                    NSLog("audioRecorder not started")
                    return false
                }
            } else {
                NSLog("audioRecorder failed to prepare")
                return false
            }

        }
    } catch let error as NSError {
        print("Error \(error.debugDescription)")
        if (self.audioRecorder != nil) {
            self.audioRecorder.stop()
            self.audioRecorder = nil
        }
        return false
    }

    return false
}

func finishRecording(sender: UIDataButton?) -> AVDataAudioRecorder? {

    var recorder: AVDataAudioRecorder? = nil

    if self.audioRecorder != nil {

        self.audioRecorder.stop()
        NSLog("audioRecorder stopped recording")
        recorder = self.audioRecorder

        AudioServicesPlayAlertSound(1111) // JBL_End

        self.audioRecorder = nil

        do {
            try self.audioSession.setActive(false)
        } catch let error as NSError {
            print("Error - AudioSession setActive False failed -  \(error.debugDescription)")
        }


        if (sender != nil) {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                sender!.setTitle("Push-to-Talk", forState: .Normal)
            })
        }
    }

But the problem is that the JBL_Begin alert sound never plays.但问题是 JBL_Begin 警报声从不播放。

Also, when I try to playback the recorded audio after recording, the volume of the audio is very low.此外,当我在录制后尝试播放录制的音频时,音频的音量非常低。 Here is my code:这是我的代码:

func pressAudioControl(sender: UIButton!) {
    if audioPlayer.playing {
        audioPlayer.pause()
        self.imageView.image = UIImage(named: "MessagePlay")
    } else {
        do {
            self.audioSession = AVAudioSession.sharedInstance()
            try self.audioSession.setCategory(AVAudioSessionCategoryPlayAndRecord, withOptions: .DefaultToSpeaker)
            try self.audioSession.setActive(true)
            self.audioPlayer.volume = 1.0
            audioPlayer.play()
            self.imageView.image = UIImage(named: "MessagePause")

        } catch let error as NSError {
            print("audioPlayer error \(error.debugDescription)")
        }
    }
}

Any idea why this problem occurs?知道为什么会出现这个问题吗?

This is due to your AVAudioSession being active when you attempt to play your system sound.这是因为当您尝试播放系统声音时,您的 AVAudioSession 处于活动状态。 You need to play your system sound with completion, then set it to true and begin recording.您需要完成播放系统声音,然后将其设置为 true 并开始录制。

AudioServicesPlaySystemSoundWithCompletion(SystemSoundID(1110)) {
    //Recording method here
}

Inside the completion block is where you will run you recording method including:在完成块内,您将运行记录方法,包括:

try self.audioSession.setActive(true)

Then before playing your ending system sound make sure to set it back to false.然后在播放结束系统声音之前,请确保将其设置回 false。

try self.audioSession.setActive(false)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM