我目前在Swift 2上使用Xcode 7 beta 4,试图播放音频。我的代码没有收到任何错误,但是当我按下“播放”按钮时,音频无法播放。我不知道出什么问题了。
import UIKit
import AVFoundation
class VesuviusViewController: UIViewController {
@IBOutlet weak var PausePlay: UIButton!
func playVes() {
do {
_ = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ves", ofType: "m4a")!))
} catch {
print("Error")
}
}
@IBAction func playButtonPressed(sender: AnyObject) {
playVes()
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
更新正确的代码:
import UIKit
import AVFoundation
class VesuviusViewController: UIViewController {
@IBOutlet weak var PausePlay: UIButton!
@IBAction func playPressed(sender: AnyObject) {
VesSet()
}
var audioPlayer: AVAudioPlayer!
func VesSet(){
do {
self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ves", ofType: "m4a")!))
self.audioPlayer.play()
} catch {
print("Error")
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
尝试这个:
var audioPlayer: AVAudioPlayer! // Global variable
和播放方法:
func playVes() {
do {
self.audioPlayer = try AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Ves", ofType: "m4a")!))
self.audioPlayer.play()
} catch {
print("Error")
}
}
希望这可以帮助!
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句