Avatar ·

如何在 iOS 应用中使用 Swift 播放声音?

大家好!我是 iOS 开发新手,正在尝试为我的应用添加音效。需要播放一个短音频文件(例如按钮点击声)。我尝试使用 AVAudioPlayer,但出了问题——声音无法播放,或者应用崩溃。 这是我的代码: ```swift import UIKit import AVFoundation class ViewController: UIViewController { var player: AVAudioPlayer? @IBAction func playSound(_ sender: UIButton) { let path = Bundle.main.path(forResource: "sound.mp3", ofType:nil)! let url = URL(fileURLWithPath: path) do { player = try AVAudioPlayer(contentsOf: url) player?.play() } catch { print("播放错误:\(error.localizedDescription)") } } } ``` 我已经将 `sound.mp3` 文件添加到项目中(拖入 Supporting Files 文件夹)。但点击按钮时没有任何反应,控制台输出错误:"The operation coul