Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift-AVAudioPlayer不';我不能正常工作_Swift_Avaudioplayer_Avaudioengine - Fatal编程技术网

Swift-AVAudioPlayer不';我不能正常工作

Swift-AVAudioPlayer不';我不能正常工作,swift,avaudioplayer,avaudioengine,Swift,Avaudioplayer,Avaudioengine,我有以下代码: let speechRecognizer = SFSpeechRecognizer()! let audioEngine = AVAudioEngine() var recognitionRequest = SFSpeechAudioBufferRecognitionRequest() var recognitionTask = SFSpeechRecognitionTask() var audioPlayer : AVAudioPlayer! override func vi

我有以下代码:

let speechRecognizer = SFSpeechRecognizer()!
let audioEngine = AVAudioEngine()
var recognitionRequest = SFSpeechAudioBufferRecognitionRequest()
var recognitionTask = SFSpeechRecognitionTask()
var audioPlayer : AVAudioPlayer!

override func viewDidLoad() {
    super.viewDidLoad()
    playSound(sound: "oops")
    speechRecognizer.delegate = self
    requestSpeechAuth()

}

func requestSpeechAuth(){
    SFSpeechRecognizer.requestAuthorization { (authStatus) in
        OperationQueue.main.addOperation({ 
            switch authStatus {
            case.authorized:
                print("authorized")
            case.denied:
                print("denied")
            case.restricted:
                print("restricted")
            case.notDetermined:
                print("not determined")
            }
        })

    }
}

// Function called when I press on my record button
func SpeechButtonDown() {
    print("Start recording")

    if audioEngine.isRunning {

        endRecording() {

    } else {
       do {

        let audioSession = AVAudioSession.sharedInstance()
        try audioSession.setCategory(AVAudioSessionCategoryRecord)
        try audioSession.setMode(AVAudioSessionModeMeasurement)
        try audioSession.setActive(true, with: .notifyOthersOnDeactivation)

        if let inputNode = audioEngine.inputNode {

            recognitionRequest.shouldReportPartialResults = true

            recognitionTask = speechRecognizer.recognitionTask(with: recognitionRequest, resultHandler: { (result, error) in
                print("1")
                if let result = result {
                    self.instructionLabel.text = result.bestTranscription.formattedString
                    print("2")
                    if result.isFinal {
                        self.audioEngine.stop()
                        inputNode.removeTap(onBus: 0)
                        if self.instructionLabel.text != "" {
                            self.compareWordwithVoice()
                        }
                    }   
                }
            })

            let recognitionFormat = inputNode.outputFormat(forBus: 0)

            inputNode.installTap(onBus: 0, bufferSize: 1024, format: recognitionFormat, block: { (buffer, when) in
                self.recognitionRequest.append(buffer)
            })

            audioEngine.prepare()

                try audioEngine.start()
       }
    } catch {

    } 
    }
}

// Function called when I release the record button
func EndRecording() {
    endRecording()
    print("Stop recording")
}

func endRecording() {
    audioEngine.stop()
    recognitionRequest.endAudio()
    audioEngine.inputNode?.removeTap(onBus: 0)
}

func playSound(sound: String) {
    if let url = Bundle.main.url(forResource: sound, withExtension: "wav") {
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: url)
            guard let player = audioPlayer else { return }
            player.prepareToPlay()
            player.play()
            print("tutu")
        } catch let error {
            print(error.localizedDescription)
        }
    }
}

func compareWordwithVoice() {

    let StringToLearn = setWordToLearn()
    print("StringToLearn : \(StringToLearn)")
    if let StringRecordedFull = instructionLabel.text{
        let StringRecorded = (StringRecordedFull as NSString).replacingOccurrences(of: " ", with: "").lowercased()
    print("StringRecorded : \(StringRecorded)")
        if StringRecorded == "appuyezsurleboutonendessousetprenoncezl’expression" {
            print("not yet")
        } else {
            if StringToLearn == StringRecorded {

        playSound(sound: "success")
        print("success")
        // update UI
    } else {
        playSound(sound: "oops")
        print("oops")
        // update UI
    }
        }

    }
}

 func setWordToLearn() -> String {
    if let wordToLearnFull = expr?.expression {
        print(wordToLearnFull)
        var wordToLearn = (wordToLearnFull as NSString).replacingOccurrences(of: " ", with: "").lowercased()
        wordToLearn = (wordToLearn as NSString).replacingOccurrences(of: ".", with: "")
        wordToLearn = (wordToLearn as NSString).replacingOccurrences(of: "!", with: "")
        wordToLearn = (wordToLearn as NSString).replacingOccurrences(of: "?", with: "")
        wordToLearn = (wordToLearn as NSString).replacingOccurrences(of: ",", with: "")
        wordToLearn = (wordToLearn as NSString).replacingOccurrences(of: "/", with: "")
        print(wordToLearn)
        return wordToLearn
    }
    print("no wordToLearn")
    return ""

}
问题是,playSound在viewDidLoad中时工作正常,但在compareThing()函数调用时不工作,但在这两种情况下都显示“tutu”,因此每次都执行playSound函数

如果AVAudioPlayer和AVAudioEngine不能同时工作,是否会出现问题

Thx

我认为“比较”总是播放“oops”的声音,这种声音不好(太安静或坏了)

请尝试从“viewDidLoad”函数中播放“oops”声音,以确保声音正常。
如果可以(我不这么认为)-在“playSound”函数中设置断点以查看发生了什么(声音名称、它是否存在等)。

我的代码也经历了同样的事情,从在线搜索来看,似乎有一个未说出口的错误“当分别使用AvAudioPlayer和引擎时”

我从下面的链接获得了信息。我没有在网上找到任何其他说明为什么会发生这个错误的信息。


建议在所有方面都使用AVAudioEngine。

是的,我没有将代码放在我使用它的地方。它在另一个函数中。据我所知,您在
if
else
中都调用了play sound。我知道,您在这两个语句中都调用了该函数是正常的。我编辑了这篇文章,把整个代码都放进去了。TY有人能帮我解决这个问题吗?oops声音在viewDidLoad()中工作得非常好,加上breackpoint,一切看起来都很好(url,声音名称),你找到什么了吗?我看到你添加了更多的源代码。但我看不到您在哪里调用“compareThings”函数,以及“thing1”和“thing1”是在哪里声明的。所以我不能复制粘贴你的代码,看看会发生什么。哦,真有趣。谢谢你的建议。