最近我在使用测试版 Xcode (7.0) 时遇到了一个问题。
我听不到我通过这段代码播放的声音:
(它是 Main.storyboard 中的一个 ViewController,有一个连接到 buttonTouchUpInside()
的按钮)
import UIKit
import AVFoundation
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func setupAudioPlayerWithFile(file:NSString, type:NSString) -> AVAudioPlayer {
let path = NSBundle.mainBundle().pathForResource(file as String, ofType: type as String)
let url = NSURL.fileURLWithPath(path!)
var audioPlayer:AVAudioPlayer?
do {
try audioPlayer = AVAudioPlayer(contentsOfURL: url)
} catch {
print("NO AUDIO PLAYER")
}
return audioPlayer!
}
@IBAction func buttonTouchUpInside(sender: AnyObject) {
let backMusic = setupAudioPlayerWithFile("sound", type: "wav")
backMusic.play()
}
}
最佳答案
您只需将 backMusic 的声明移出您的 IBAction:
像这样尝试:
class ViewController: UIViewController {
var backMusic: AVAudioPlayer!
// ...
@IBAction func buttonTouchUpInside(sender: AnyObject) {
backMusic = setupAudioPlayerWithFile("sound", type: "wav")
backMusic.play()
}
}
关于iOS Swift 2.0 - AvAudioPlayer 没有播放任何声音,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30873056/