'Need help adding an audio file to a button in swift [closed]
can anyone help me get this to work I am a noob programer and I could not find a way to do this.
Code below
import UIKit
class ViewController: UIViewController {
@IBAction func pistolButton(sender: AnyObject) {
}
override func viewDidLoad() { // I want my audio file to play when button is tapped
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
Solution 1:[1]
First drag your sound to your project and choose to copy for your destination if needed and check "add to target" to your app. Create a function to play your sound and you need also to add import AVFoundation at the beginning of your code as bellow:
import AVFoundation
let beepSoundURL = NSBundle.mainBundle().URLForResource("beep", withExtension: "aif")!
var beepPlayer = AVAudioPlayer()
func playMySound(){
beepPlayer = AVAudioPlayer(contentsOfURL: beepSoundURL, error: nil)
beepPlayer.prepareToPlay()
beepPlayer.play()
}
@IBAction func pistolButton(sender: AnyObject) {
playMySound()
}
Solution 2:[2]
There is a lot of pretty good code on Stack Overflow:
Playing a sound with AVAudioPlayer
Here is some example code:
import AVFoundation
var audioPlayer: AVAudioPlayer?
if let path = NSBundle.mainBundle().pathForResource("mysound", ofType: "aiff") {
audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path), fileTypeHint: "aiff", error: nil)
if let sound = audioPlayer {
sound.prepareToPlay()
sound.play()
}
}
from this location:
http://www.reddit.com/r/swift/comments/28izxl/how_do_you_play_a_sound_in_ios/
Solution 3:[3]
Swift 3
the syntax is now as follows:
import UIKit
import AVFoundation
class ViewController: UIViewController {
var audioPlayer = AVAudioPlayer()
override func viewDidLoad() {
super.viewDidLoad()
// address of the music file
let music = Bundle.main.path(forResource: "Music", ofType: "mp3")
do {
audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
}
catch{
print(error)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func play(_ sender: AnyObject) {
audioPlayer.play()
}
@IBAction func stop(_ sender: AnyObject) {
audioPlayer.stop()
}
}
Solution 4:[4]
Swift 5.5 version syntax.`
import AVFoundation
let beepSoundURL = Bundle.main.url(forResource: "gosound", withExtension: "wav")
var beepPlayer = AVAudioPlayer()
func playMySound(){
if let soundGo = beepSoundURL {
do {
try beepPlayer = AVAudioPlayer(contentsOf: soundGo, fileTypeHint: nil)
}
catch {
print ("error")
}
}
beepPlayer.prepareToPlay()
beepPlayer.play()
}
@IBAction func pistolButton(sender: AnyObject) {
playMySound()
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Community |
| Solution 3 | MiladiuM |
| Solution 4 | Ahmet Sina |
