我正在尝试按下按钮,按下按钮时会发出声音。
我的应用程序有6个按钮(有6种不同的声音)。我只列出了一个,因为我试图在完成剩下的工作之前让一个按钮正常工作。我知道按钮正在工作(从底部的打印命令),但它没有播放声音。
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var player : AVAudioPlayer?
@IBAction func buttonOne(_ sender: Any) {
func playSound() {
let url = Bundle.main.url(forResource: "drinking", withExtension: "mp3")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error as NSError {
print(error.description)
}
}
print("Anakin: IT IS WORKING!")
}
}
答案 0 :(得分:0)
是否打印出任何错误?
你能尝试这样做吗?
let path = Bundle.main.path(forResource: "FILE NAME WITH EXTENSION", ofType:nil)!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
sound.play()
} catch {
// couldn't load file :(
}