您好我正在尝试使用以下代码在 swift 2中播放音乐文件.基本上我只是将名为f.mp3的音频文件拖到asses文件夹中,我的代码中断了以下消息: 在展开Optional值时意外地发现了nil.我需要把我的
在展开Optional值时意外地发现了nil.我需要把我的mp3文件放在哪里,以便 IOS可以找到它.谢谢
var audioPlayer: AVAudioPlayer! = nil func playMyFile() { let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3") let fileURL = NSURL(fileURLWithPath: path) do { try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL) } catch { print("error") } audioPlayer.prepareToPlay() audioPlayer.delegate = self audioPlayer.play() }您的代码在我的项目中正常运行,这是我的完整代码:
import UIKit import AVFoundation class ViewController: UIViewController { var audioPlayer: AVAudioPlayer! = nil override func viewDidLoad() { super.viewDidLoad() playMyFile() } func playMyFile() { let path = NSBundle.mainBundle().pathForResource("f", ofType: "mp3") let fileURL = NSURL(fileURLWithPath: path!) do { try audioPlayer = AVAudioPlayer(contentsOfURL: fileURL) } catch { print("error") } audioPlayer.prepareToPlay() audioPlayer.play() } }
确保将音频添加到Copy Bundle Resources中,如下所示:
如果没有添加,请以这种方式添加:
查看THIS样本以获取更多信息.