如何在按下button的情况下在swift 2中播放m4a文件?

当我触摸一个button时,如何播放audio文件,没有任何工作可以在网上find,因为它的速度很快。

我想要originalfunction中的audio代码。

 import UIKit import AVFoundation class ViewController: UIViewController { @IBAction func original(sender: AnyObject) { } } 

这里有一些代码可以帮助你:

Swift 3

 import UIKit import AVFoundation class ViewController: UIViewController { let player = AVQueuePlayer() @IBAction func original(sender: AnyObject) { if let url = Bundle.main.url(forResource: "sample_song", withExtension: "m4a") { player.removeAllItems() player.insert(AVPlayerItem(url: url), after: nil) player.play() } } } 

Swift 2

 import UIKit import AVFoundation class ViewController: UIViewController { let player = AVQueuePlayer() @IBAction func original(sender: AnyObject) { if let url = NSBundle.mainBundle().URLForResource("SomeAudioFile", withExtension: "m4a") { player.removeAllItems() player.insertItem(AVPlayerItem(URL: url), afterItem: nil) player.play() } } } 

你没有解释如果button被多次击中会发生什么,所以我假定你想停止正在播放的当前项目并开始一个新的。