如何在swift3中使用此代码创建函数?
我有一个按下按钮然后播放此声音"按下#34;
有很多按钮时如何简化?我不想将所有代码添加到每个按钮。
var myAudio = AVAudioPlayer()
// Add sound
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: "push", ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
//call the sound
myAudio.play()
我做了这个改变
func play(name : String){
do {
try myAudio = AVAudioPlayer(contentsOf: NSURL(fileURLWithPath:
Bundle.main.path(forResource: name, ofType: "mp3")!) as URL)
} catch {
NSLog("No file!")
}
}
@IBAction func buttonFirst(_ sender: UIButton) {
play(name: "push")
myAudio.play()
}
@IBAction func buttonSecond(_ sender: UIButton) {
play(name: "second")
myAudio.play()
}
我得到了这个输出:
2017-07-25 16:13:23.270349 + 0100声音[1728:933024] [aqme] 254:AQDefaultDevice(173):跳过输入流0 0 0x0
这是一个问题吗?
答案 0 :(得分:0)
我想你忘记了准备
StoredFileObserver
答案 1 :(得分:0)
您可以按以下方式使用
var myAudio : AVAudioPlayer?
func playSound(){
let path = Bundle.main.path(forResource: "push", ofType:"mp3")!
let url = URL(fileURLWithPath: path)
do {
let sound = try AVAudioPlayer(contentsOf: url)
self.myAudio = sound
sound.numberOfLoops = 1
sound.prepareToPlay()
sound.play()
} catch {
print("error loading file")
// couldn't load file :(
}
}
此外,您可以使用SwiftySound让您轻松在Swift 3中播放声音。 例如
Sound.play(file: "push.mp3")