如何根据swift 3语法编写此代码?

时间:2017-02-26 03:59:46

标签: swift3 swift2

我正在尝试让我的应用播放声音,此代码是我的Udemy课程中提供的资源(适用于Swift 2 :()

func playSound(fileName: String, fileExtension: String) throws {
        super.viewDidLoad()

    let dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

    dispatch_async(dispatchQueue, { let mainBundle = NSBundle.mainBundle()

        let filePath = mainBundle.pathForResource("\(fileName)", ofType:"\(fileExtension)")

        if let path = filePath{
            let fileData = NSData(contentsOfFile: path)

            do {
                /* Start the audio player */
                self.audioPlayer = try AVAudioPlayer(data: fileData!)

                guard let player : AVAudioPlayer? = self.audioPlayer else {
                    return
                }

                /* Set the delegate and start playing */
                player!.delegate = self
                if player!.prepareToPlay() && player!.play() {
                    /* Successfully started playing */
                } else {
                    /* Failed to play */
                }

            } catch {
                //self.audioPlayer = nil
                return
            }

        }

    })

}

我正在尝试让我的应用播放声音,此代码是我的Udemy课程中提供的资源(适用于Swift 2 :()

1 个答案:

答案 0 :(得分:0)

这里是Swift 3中相同的方法实现:

func playSound(fileName: String, fileExtension: String) throws {

    let dispatchQueue = DispatchQueue.global()

    dispatchQueue.async(execute: { 

        let filePath = Bundle.main.path(forResource: "\(fileName)", ofType:"\(fileExtension)")

        if let path = filePath{

            do {
                let fileData = try Data(contentsOf: URL(fileURLWithPath: path))

                /* Start the audio player */
                let audioPlayer = try AVAudioPlayer(data: fileData)

                /* Set the delegate and start playing */
                audioPlayer.delegate = self
                if audioPlayer.prepareToPlay() && audioPlayer.play() {
                    /* Successfully started playing */
                } else {
                    /* Failed to play */
                }

            } catch {
                //self.audioPlayer = nil
                return
            }

        }
    })
}

您可以在此处看到一些更改:

  • 现代化调度(dispatch_get_global_queue - > Dispatch.global()
  • 删除NS前缀(NSBundle - > BundleNSData - > Data

您可以在these等文章中看到其他此类更改的列表。