在 Swift 中实现长按录制声音并转换成文字,可以按照以下步骤进行:

  1. 导入 AVFoundation 框架:在你的 Swift 文件的顶部添加 import AVFoundation

  2. 创建一个 AVAudioRecorder 实例来录制声音:

var audioRecorder: AVAudioRecorder!
  1. 初始化 AVAudioRecorder:
func initAudioRecorder() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.wav")
    let settings = [
        AVFormatIDKey: Int(kAudioFormatLinearPCM),
        AVSampleRateKey: 44100,
        AVNumberOfChannelsKey: 2,
        AVEncoderAudioQualityKey: AVAudioQuality.high.rawValue
    ]
    
    do {
        audioRecorder = try AVAudioRecorder(url: audioFilename, settings: settings)
        audioRecorder.delegate = self
    } catch {
        print("Failed to initialize audio recorder: \(error)")
    }
}
  1. 开始录制声音:
func startRecording() {
    if audioRecorder == nil {
        initAudioRecorder()
    }
    
    if audioRecorder.isRecording {
        audioRecorder.stop()
    }
    
    audioRecorder.record()
}
  1. 停止录制声音:
func stopRecording() {
    audioRecorder.stop()
}
  1. 创建一个 AVAudioPlayer 实例来播放录制的声音:
var audioPlayer: AVAudioPlayer!
  1. 初始化 AVAudioPlayer:
func initAudioPlayer() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.wav")
    
    do {
        audioPlayer = try AVAudioPlayer(contentsOf: audioFilename)
        audioPlayer.delegate = self
        audioPlayer.prepareToPlay()
    } catch {
        print("Failed to initialize audio player: \(error)")
    }
}
  1. 播放录制的声音:
func playRecording() {
    if audioPlayer == nil {
        initAudioPlayer()
    }
    
    if audioPlayer.isPlaying {
        audioPlayer.stop()
    }
    
    audioPlayer.play()
}
  1. 创建一个 SpeechRecognizer 实例来将录制的声音转换成文字:
var speechRecognizer: SFSpeechRecognizer!

func initSpeechRecognizer() {
    speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))
    speechRecognizer.delegate = self
}
  1. 转换录制的声音为文字:
func convertRecordingToText() {
    let audioFilename = getDocumentsDirectory().appendingPathComponent("recording.wav")
    let recognitionRequest = SFSpeechURLRecognitionRequest(url: audioFilename)
    
    speechRecognizer.recognitionTask(with: recognitionRequest) { (result, error) in
        guard let result = result else {
            print("Failed to convert recording to text: \(error)")
            return
        }
        
        if result.isFinal {
            let text = result.bestTranscription.formattedString
            print("Converted text: \(text)")
        }
    }
}
  1. 设置长按手势来控制录制和转换:
func setupLongPressGestureRecognizer() {
    let longPressGestureRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(handleLongPress(_:)))
    longPressGestureRecognizer.minimumPressDuration = 0.5
    longPressGestureRecognizer.delegate = self
    yourButton.addGestureRecognizer(longPressGestureRecognizer)
}

@objc func handleLongPress(_ gestureRecognizer: UILongPressGestureRecognizer) {
    if gestureRecognizer.state == .began {
        startRecording()
    } else if gestureRecognizer.state == .ended {
        stopRecording()
        convertRecordingToText()
    }
}

请确保在使用之前允许应用程序访问麦克风和语音识别权限,并实现 AVAudioRecorderDelegateAVAudioPlayerDelegateSFSpeechRecognizerDelegate 协议中的必要方法。

以上是一个基本的实现,你可以根据你的需求进行修改和扩展

swift 长按录制声音然后放开按钮转换成文字

原文地址: http://www.cveoy.top/t/topic/iGjb 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录