简体   繁体   English

音频未播放 Xcode 10.1 Swift 4

[英]Audio is not playing Xcode 10.1 Swift 4

I finally started learning to play sounds but I'm not succeeding in playing sounds in my app.我终于开始学习播放声音,但我没有成功在我的应用程序中播放声音。 I'm still on Xcode 10.1/Swift4 (not 4.2) as I'm not able to upgrade to Mojave/Catalina yet.我仍然使用 Xcode 10.1/Swift4(不是 4.2),因为我还不能升级到 Mojave/Catalina。 I read quite a few posts about .setCategory(.playback, mode: .default) carrying a bug in Xcode 10.1 but solutions found are for Swift 4.2.我阅读了很多关于.setCategory(.playback, mode: .default)在 Xcode 10.1 中携带错误的帖子.setCategory(.playback, mode: .default)但找到的解决方案适用于 Swift 4.2。 Also category: and mode: are expected to be of type String ,but on docs the function is explained as:另外category:mode:应该是String类型,但在文档中,函数被解释为:

func setCategory(_ category: AVAudioSession.Category, mode: AVAudioSession.Mode, options: AVAudioSession.CategoryOptions = []) throws func setCategory(_ category: AVAudioSession.Category, mode: AVAudioSession.Mode, options: AVAudioSession.CategoryOptions = []) 抛出

and they're not of type String .并且它们不是String类型。 I'm a bit lost here.我有点迷失在这里。

My code doesn't throw any compiling error, but at runtime on console I get :我的代码没有抛出任何编译错误,但在控制台运行时我得到:

AVAudioSessionUtilities.mm:106:getUInt32: -- Category Value Converter failed to find a match for string "ambient" AVAudioSessionUtilities.mm:106:getUInt32: -- 类别值转换器未能找到字符串“ambient”的匹配项

What am I missing here?我在这里缺少什么? Can you please point me in the right direction to understand this category problem?你能指出我正确的方向来理解这个类别问题吗? As always thank you very much for your time and help.一如既往,非常感谢您的时间和帮助。

This is the function that should play sounds :这是应该播放声音的功能:

static func playOnceSound(soundToPlay: String) {
       var player: AVAudioPlayer?
        guard let url = Bundle.main.url(forResource: soundToPlay, withExtension: "mp3") else { return }



        do {
//            try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default) // Error: Type 'String' has no member 'playback'

            try AVAudioSession.sharedInstance().setCategory("ambient", mode: "default", options: .defaultToSpeaker)
            try AVAudioSession.sharedInstance().setActive(true)

            /* The following line is required for the player to work on iOS 11. Change the file type accordingly*/
            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)

            /* iOS 10 and earlier require the following line:
             player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileTypeMPEGLayer3) */

            guard let player = player else { return }
            player.numberOfLoops = 1
            player.volume = 1.0
            player.play()

        } catch let error {
            print(error.localizedDescription)
        }
    }

Have you tried inputting ambient & default this way, instead of using a string?您是否尝试过以这种方式输入环境和默认值,而不是使用字符串? Also, instantiating the audio session object before setCategory:此外,在 setCategory 之前实例化音频会话对象:

var audioSession: AVAudioSession?

func setup() {
    audioSession = AVAudioSession.sharedInstance()

    do {
        try audioSession.setCategory(AVAudioSession.Category.ambient, mode: .default, options: .defaultToSpeaker)
        try audioSession.setActive(true)
    }
    catch {
        print("Failed to set category", error.localizedDescription)
    }
}
@IBAction func doPlay1(_ sender: AnyObject) {
    do{
        self.audioPlayer = try AVAudioPlayer(contentsOf: URL.init(string: url)!)
        self.audioPlayer.prepareToPlay()
        self.audioPlayer.delegate = self
        self.audioPlayer.play()
    }catch{
        print(error.localizedDescription)
    }
}

So I just set it in AppDelegate didFinishLaunchingWithOptions as :所以我只是在AppDelegate didFinishLaunchingWithOptions中将它设置为:

 do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
        } catch let error1 as NSError{
            error = error1
            print("could not set session. err:\(error!.localizedDescription)")
        }
        do {
            try AVAudioSession.sharedInstance().setActive(true)
        } catch let error1 as NSError{
            error = error1
            print("could not active session. err:\(error!.localizedDescription)")
        } 

and rewrote the function as :并将函数重写为:

static func playOnceSound(soundToPlay: String) {
        if Sounds.player!.isPlaying == true {
            Sounds.player!.stop()
        }

        let url = URL(fileURLWithPath: Bundle.main.path(forResource: soundToPlay, ofType: "mp3")!)

        var error: NSError?

        do {
            Sounds.player = try AVAudioPlayer(contentsOf: url)
        } catch let error1 as NSError {
            error = error1
            Sounds.player = nil
        }

        if let err = error {
            print("audioPlayer error \(err.localizedDescription)")
            return
        } else {
            Sounds.player!.prepareToPlay()
        }
        //negative number means loop infinity
        Sounds.player!.numberOfLoops = 0
        Sounds.player!.volume = Sounds.volume
        Sounds.player!.play()

    }

Thanks for your help, and I hope this will be of help to others.感谢您的帮助,我希望这对其他人有所帮助。 Cheers.干杯。

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

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