我正在尝试有一个按钮,按下时会发出声音。
我的应用程序有 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!")
}
}
最佳答案
打印有错误吗?
你能尝试这样做吗?
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 :(
}
关于iphone - 按下按钮时的 Swift AVAudioplayer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45682372/