修复错误AudioPlayer

时间:2016-09-13 17:58:54

标签: ios objective-c swift

我在var filePathUrl的行中收到错误。错误代码是“可选类型的值'字符串?'没打开:你的意思是用'!'要么 '?'?'”。我该如何解决这个错误?

import UIKit
import AVFoundation

class PlayMusicViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.

         var daten = NSBundle.mainBundle().pathForResource("Kool_Savas_Auge", ofType: "mp3")
            var filePathUrl = NSURL.fileURLWithPath(daten)
        var audioPlayer = AVAudioPlayer(contentsOfURL: filePathUrl, fileTypeHint: nil)


    }

    @IBAction func PlayMusic(sender: UIButton) {
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

1 个答案:

答案 0 :(得分:0)

尝试

var filePathUrl = NSURL.fileURLWithPath(daten!)
  

你能告诉我我做错了吗?

enter image description here

在可选值之后的感叹号(!)以强制展开其值。请检查一下 Swift 2: !, ? -" Value of optional type "..." not unwrapped"

更新:

例如:

var daten = NSBundle.mainBundle().pathForResource("Kool_Savas_Auge", ofType: "mp3")

    var filePathUrl = NSURL.fileURLWithPath(daten!)

    do{
        var audioPlayer = try AVAudioPlayer(contentsOfURL: filePathUrl, fileTypeHint: nil)

        audioPlayer.prepareToPlay()
        audioPlayer.play()
    }
    catch let err as NSError{
        print(err.debugDescription);
    }