ios - AVAudioSession 从未停止

标签 ios swift swift3 avaudiosession

我正在尝试将我的 AVAudioSession 设置为非事件状态以恢复正常状态。

我的话语功能:

class SSpeech : NSObject, AVSpeechSynthesizerDelegate {

    var group = DispatchGroup();
    var queue = DispatchQueue(label: "co.xxxx.speech", attributes: [])

    class var sharedInstance: SSpeech {
        struct Static {
            static var instance: SSpeech?
        }
        if !(Static.instance != nil) {
            Static.instance = SSpeech()
        }
       return Static.instance!
    }

   required override init() {
       super.init();
       self.speechsynt.delegate = self;
   }

   deinit {
      print("deinit SSpeech")
   }

   let audioSession = AVAudioSession.sharedInstance();
   var speechsynt: AVSpeechSynthesizer = AVSpeechSynthesizer()
   var queueTalks = SQueue<String>();

   func pause() {
        speechsynt.pauseSpeaking(at: .word)
   }

   func talk(_ sentence: String, languageCode code:String = SUtils.selectedLanguage.code, withEndPausing: Bool = false) {
       if SUser.sharedInstance.currentUser.value!.speechOn != 1 {
           return
        }

        queue.async{            
            self.queueTalks.enQueue(sentence)
            do {
                let category = AVAudioSessionCategoryPlayback;
                var categoryOptions = AVAudioSessionCategoryOptions.duckOthers
                if #available(iOS 9.0, *) {
                    categoryOptions.formUnion(AVAudioSessionCategoryOptions.interruptSpokenAudioAndMixWithOthers)
                 }
                try self.audioSession.setCategory(category, with: categoryOptions)
                try self.audioSession.setActive(true);
            } catch _ {
                return;
            }

            self.utteranceTalk(sentence, initSentence: false, speechsynt: self.speechsynt, languageCode:code, withEndPausing: withEndPausing)

            do {
                try self.audioSession.setCategory(AVAudioSessionCategoryPlayback, with: AVAudioSessionCategoryOptions.mixWithOthers)
            } catch _ {
                return;
            }
        }
    }

    func utteranceTalk(_ sentence: String, initSentence: Bool, speechsynt: AVSpeechSynthesizer, languageCode:String = "en-US", withEndPausing: Bool = false){
        if SUser.sharedInstance.currentUser.value!.speechOn != 1 {
            return
        }

        let nextSpeech:AVSpeechUtterance = AVSpeechUtterance(string: sentence)
        nextSpeech.voice = AVSpeechSynthesisVoice(language: languageCode)
        if !initSentence {
            nextSpeech.rate = 0.4;
        }

        if(withEndPausing){
            nextSpeech.postUtteranceDelay = 0.2;
        }
        speechsynt.speak(nextSpeech)
    }


    func speechSynthesizer(_ synthesizer: AVSpeechSynthesizer, didFinish utterance:AVSpeechUtterance) {
        print("Speaker has finished to talk")

        queue.async {
               do {
                   try self.audioSession.setActive(false, with: AVAudioSessionSetActiveOptions.notifyOthersOnDeactivation)
               }
               catch {}
           }
       }
    }
}

我的方法被正确调用,但是当 utterance 结束时,我的 audioSession 仍然处于事件状态。我已经尝试了很多东西,但没有任何效果 :(。

最佳答案

我建议使用 AvAudioPlayer。它们具有非常简单的启动和停止命令。

首先将音频播放器声明为变量

var SoundEffect: AVAudioPlayer!

然后选择你需要的文件

    let path = Bundle.main.path(forResource: "Untitled2.wav", ofType:nil)!
                    let url = URL(fileURLWithPath: path)
    let sound = try AVAudioPlayer(contentsOf: url)
                        SoundEffect = sound
                        sound.numberOfLoops = -1
                        sound.play()

并停止音频播放器

if SoundEffect != nil {
            SoundEffect.stop()
            SoundEffect = nil
        }

关于ios - AVAudioSession 从未停止,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43373486/

相关文章:

ios - uiwebview vs wkwebview,一个可以加载内容,一个不能

ios - 如何在没有 Storyboard的容器 View 中打开 View Controller

javascript - Socket IO Swift 客户端发送带有 ACK 的消息

ios - 键盘在 Web View 中未正确显示 - 横向模式

swift - AVPlayer seekToTime 无法正常工作

ios - swift-如何在特定日期和时间打开日历应用程序?

ios - 更改 Carthage Swift 版本

ios - YTPlayerView youtube-ios-player-helper 暂停不工作

ios - 我的类别 NSDate+Api 现在不适用于 Swift 中的 Date 类(迁移到 Swift 3 和 Swift 互操作性之后)

ios - 如何在 swift 3 中动态增加 ScrollView 高度的高度?