2017-02-12 2 views
0

기본적으로 저는 현재 제작중인 앱에 음성 인식을 통합하려고합니다. 마이크 버튼을 눌렀을 때 소리를 내고 녹음을 시작하고 오디오를 인식하고 싶습니다. 문제는 버튼을 누르면 소리가 나지 않는다는 것입니다. 또한 실제 iPhone에서 앱을 실행하면 제어판의 사운드 슬라이더가 사라집니다. 아무도 도와 줄 수 있니?스위프트 3 오디오가 재생되지 않습니다.

class VoiceViewController: UIViewController, SFSpeechRecognizerDelegate, UITextViewDelegate { 

private let speechRecognizer = SFSpeechRecognizer(locale: Locale(identifier: "en-US"))! 
private var speechRecognitionRequest: SFSpeechAudioBufferRecognitionRequest? 
private var speechRecognitionTask: SFSpeechRecognitionTask? 
private let audioEngine = AVAudioEngine() 

var audioPlayer: AVAudioPlayer = AVAudioPlayer() 
var url: URL? 
var recording: Bool = false 

let myTextView = UITextView() 

func startSession() throws { 

    if let recognitionTask = speechRecognitionTask { 
     recognitionTask.cancel() 
     self.speechRecognitionTask = nil 
    } 

    let audioSession = AVAudioSession.sharedInstance() 
    try audioSession.setCategory(AVAudioSessionCategoryRecord) 

    speechRecognitionRequest = SFSpeechAudioBufferRecognitionRequest() 

    guard let inputNode = audioEngine.inputNode else { fatalError("Audio engine has no input node") } 

    speechRecognitionRequest?.shouldReportPartialResults = true 

    speechRecognitionTask = speechRecognizer.recognitionTask(with: speechRecognitionRequest!) { result, error in 

     var finished = false 

     if let result = result { 
      print(result.bestTranscription.formattedString) 
      finished = result.isFinal 
     } 

     if error != nil || finished { 
      self.audioEngine.stop() 
      inputNode.removeTap(onBus: 0) 

      self.speechRecognitionRequest = nil 
      self.speechRecognitionTask = nil 
     } 
    } 

    let recordingFormat = inputNode.outputFormat(forBus: 0) 
    inputNode.installTap(onBus: 0, bufferSize: 1024, format: recordingFormat) { (buffer: AVAudioPCMBuffer, when: AVAudioTime) in 

     self.speechRecognitionRequest?.append(buffer) 
    } 

    audioEngine.prepare() 
    try audioEngine.start() 
} 

func stopTranscribing() { 
    if audioEngine.isRunning { 
     audioEngine.stop() 
     speechRecognitionRequest?.endAudio() 
    } 
} 

func btn_pressed() { 
    print("pressed") 

    if recording { 
     url = URL(fileURLWithPath: Bundle.main.path(forResource: "tweet", ofType: "mp3")!) 
    } else { 
     url = URL(fileURLWithPath: Bundle.main.path(forResource: "gesture", ofType: "mp3")!) 
    } 

    do { 
     try(audioPlayer = AVAudioPlayer(contentsOf: url!)) 
    } catch let err { 
     print(err) 
    } 
    audioPlayer.play() 
    recording = (recording == false) 
    if recording == false { 
     stopTranscribing() 
    } else { 
     try! startSession() 
    } 
} 

override func viewDidLoad() { 
    super.viewDidLoad() 

    let button = UIButton() 
    button.setTitle("push me", for: UIControlState()) 
    button.frame = CGRect(x: 10, y: 30, width: 80, height: 30) 
    button.addTarget(self, action: #selector(btn_pressed), for: .touchUpInside) 
    self.view.addSubview(button) 

    myTextView.frame = CGRect(x: 60, y: 100, width: 300, height: 200) 
    self.view.addSubview(myTextView) 


    // Do any additional setup after loading the view. 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 


/* 
// MARK: - Navigation 

// In a storyboard-based application, you will often want to do a little preparation before navigation 
override func prepare(for segue: UIStoryboardSegue, sender: AnyObject?) { 
    // Get the new view controller using segue.destinationViewController. 
    // Pass the selected object to the new view controller. 
} 
*/ 

} 

답변

1

이 문서 말 : 여기

내 코드입니다

AVAudioSessionCategoryRecord 오디오를 기록 카테고리; 이 범주는 재생 오디오를 음소거합니다.

사용하는 유일한 오디오 세션 범주이며 AVAudioPlayer를 재생하려고하면 바로 설정되므로 자연스럽게 아무 것도들을 수 없습니다. 민첩하고 정확한 오디오 세션을 생각해보십시오. 사운드를 재생 한 다음 녹음을 시작하려면 재생 범주를 사용하여 사운드를 재생하고 AVAudioPlayerDelegate를 통해 사운드가 완료되었다는 메시지가 나타날 때까지 녹음을 시작하지 마십시오.

+0

별도의 오디오 세션 카테고리 2 개를 사용할 수 있습니까? 그래서 나는 오디오가 재생되는 동안 녹음 할 수 있습니다. –

+0

AVAudioSessionCategoryPlayAndRecord의 용도는 무엇입니까? 하지만 유스 케이스에서는 좋지 않은 아이디어라고 생각합니다. 추가 사운드를 재생하는 동안 컴퓨터가 어떻게 음성을 인식합니까? – matt

+0

그냥 빨리 1 초 음질을 재생하려고합니다. –

관련 문제