在Xcode 9.2中播放声音

时间:2018-04-02 21:36:52

标签: swift xcode avfoundation

我在Xcode 9.2中播放声音时遇到了一些问题。 我试着看几个不同的教程和指南,但没有运气。 这两个代码都已过时,我的应用程序崩溃,声音不起作用,或者它启动并在几毫秒后切断......

    func updateDiceImages() {

// This is where the actual sound is attempted to play, 
it should be triggered every time the button is pressed. Rest of the app works fine.

        var soundEffect: AVAudioPlayer?

        let path = Bundle.main.path(forResource: "rollingDice.wav", ofType:nil)!
        let url = URL(fileURLWithPath: path)

        do {
            soundEffect = try AVAudioPlayer(contentsOf: url)
            soundEffect?.play()
        } catch {
            print(error)
        }

...

我只是不确定我做错了什么,尝试了很多变化。 我完全愿意提供我能提供的任何信息。我没有粘贴整个代码,所以它不会打扰或淹没试图阅读它的人。 非常感谢你的帮助! =)

1 个答案:

答案 0 :(得分:0)

这是我的一个应用程序中的一段代码,它完全有效。

import AVFoundation

final class AudioManager {

    private init() { }

    static let shared = AudioManager()

    private var player: AVAudioPlayer?

    enum SoundType {
        case incomingCall
    }

    open func playSound(_ type: SoundType) {
        switch type {
        case .incomingCall:
            playIncomingCall()
        }
    }

    // MARK: - Sounds

    private func playIncomingCall() {
        guard let url = Bundle.main.url(forResource: "incoming", withExtension: "wav") else { return }
        playSound(url)
    }

    private func playSound(_ url: URL) {
        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try AVAudioSession.sharedInstance().setActive(true)

            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.wav.rawValue)

            guard let player = player else { return }
            player.numberOfLoops = -1 // infinity loop
            player.prepareToPlay()
            player.play()
            debugPrint("playSound play sound")
        } catch {
            debugPrint(error.localizedDescription)
        }
    }

    open func stop() {
        player?.stop()
    }

}