如何在 swift 5 上播放声音?

问题描述 投票:0回答:1

func playSound() { guard let url = Bundle.main.url(forResource: "C", withExtension: "wav") else { 返回 }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        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.play()

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

//在 swift 5

上播放声音
swift audio playback
1个回答
0
投票

func playSound() { guard let url = Bundle.main.url(forResource: "C", withExtension: "wav") else { 返回 }

    do {
        try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
        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.play()

    } catch let error {
        print(error.localizedDescription)
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.