只需按一下按钮,如何在swift 2中播放m4a文件?

Ale*_*ker 1 audio ios swift swift2

当我触摸按钮时,如何播放音频文件,没有什么工作可以在网上找到,因为它全部快速1.

我想要功能中的音频代码original.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    @IBAction func original(sender: AnyObject) {        
    }
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*ntz 7

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

斯威夫特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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

斯威夫特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()
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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