我想在单击按钮时播放小 mp3 文件。但不知道如何在 setPathForResources 中设置 mp3 文件
这是我的代码
import UIKit
import AVFoundation
class PlaySoundsViewController: UIViewController {
var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("/sounds/superman", ofType: "mp3")!)
var audioPlayer = AVAudioPlayer()
@IBOutlet weak var PlaySlow: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func PlaySlowAction(sender: UIButton) {
audioPlayer.play()
}
我仅通过拖放即可将 sounds
文件夹添加到项目中。但是当我单击按钮时,我收到此错误。
audioPlayer.play()线程1:EXC_BAD_ACCESS(Code=1,address=0x1c)
最佳答案
您不需要 sounds/
在你的道路上。只是文件名。例如
var coinSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")!)
还有fileURLWithPath
接受一个 URL,而不是一个字符串。您需要转换您的NSBundle.mainBundle().pathForResource("superman", ofType: "mp3")
首先使用 NSURL(string:)
到字符串.
这是完整的设置:
let path = NSBundle.mainBundle().pathForResource("superman", ofType:"mp3")
let fileURL = NSURL(fileURLWithPath: path)
player = AVAudioPlayer(contentsOfURL: fileURL, error: nil)
player.prepareToPlay()
player.delegate = self
player.play()
关于iOS AVAudioPlayer - 如何将文件路径设置为pathForResource,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27604345/