Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) {        
    }
}
like image 625
Alex Walker Avatar asked Sep 02 '25 05:09

Alex Walker


2 Answers

Here is some code to get you going:

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

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.

like image 157
Stefan Arentz Avatar answered Sep 04 '25 22:09

Stefan Arentz


if let url = NSBundle.mainBundle().URLForResource("SomeAudioFile", withExtension: "m4a") {
            player.removeAllItems()
            player.insertItem(AVPlayerItem(URL: url), afterItem: nil)
            player.play()
        } else {

print("Go to your Build Phases/Copy Bundle Resources to make sure that your music file IS INDEED there. If not, drag it from the Navigator pane into the Copy Bundle Resources folder.")
}
like image 22
scott Avatar answered Sep 04 '25 21:09

scott