在Xcode 7中播放audio/ Swift 2不工作

我目前在Xcode 7 beta 4上使用Swift 2,试图播放audio。 我的代码中没有出现任何错误,但是当按下播放button时,audio不能播放。 我弄不清楚什么是错的。

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") } } 

希望这可以帮助!

当前的代码工作在xCode 7.0 Swift 2.0仍然工作于2015年10月9日

 //Declaration var hitSoundPlayer: AVAudioPlayer? //Added into the didMoveToView(view: SKView) Function do { hitSoundPlayer = try AVAudioPlayer(contentsOfURL: hitSound) hitSoundPlayer!.prepareToPlay() } catch _ { hitSoundPlayer = nil } //When you want to play it hitSoundPlayer!.play() 

不知道为什么这发生在你身上,但有多种方式实施声音到你的项目。 试试这个方法:

 class Hello : UIViewController { var Audio1 = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("mySound", ofType: "wav")!) var AudioPlayer = AVAudioPlayer() override func viewDidLoad() { AudioPlayer = AVAudioPlayer(contentsOfURL: Audio1, error: nil) } func playsound() { AudioPlayer.play() }