Alex Walker Alex Walker - 5 months ago 67
Swift Question

How do I play an m4a file in swift 2 upon the touch of a button?

How do I play an audio file when I touch a button, nothing is working that i can find online because its all swift 1.

I want the audio code in the

original
function.

import UIKit
import AVFoundation

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

Answer

Here is some code to get you going:

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

You did not explain what should happen if the button is hit multiple times, so I assumed that you would want to stop the current item being played and start a new one.