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) {
}
}
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.
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.")
}
Swift 5 update:
if let url = Bundle.main.url(forResource: "SomeAudioFile", withExtension: "m4a") {
player.removeAllItems()
player.insert(AVPlayerItem(url: url), after: nil)
player.play()
}