18

I'm very beginner of programming and start studying Swift to make a piano app for fun.

I have a trouble to play a sound when press a button. I've searched some website but I'm too beginner to understand...

http://www.tmroyal.com/playing-sounds-in-swift-avaudioplayer.html http://www.rockhoppertech.com/blog/swift-avfoundation/

Could you please tell me how can I play my "C.m4a" sound when press a "PainoC" button?

Here is my "view controller.swift".

import UIKit

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()   
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    @IBAction func PianoC(sender: AnyObject) {
    }
}

8 Answers 8

36

I hope it will help you.

import UIKit
import AVFoundation

class ViewController: UIViewController {
   // make sure to add this sound to your project
   var pianoSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("C", ofType: "m4a"))
   var audioPlayer = AVAudioPlayer()

   override func viewDidLoad() {
       super.viewDidLoad()   

       audioPlayer = AVAudioPlayer(contentsOfURL: pianoSound, error: nil)
       audioPlayer.prepareToPlay()
   }

   override func didReceiveMemoryWarning() {
       super.didReceiveMemoryWarning()
   }

   @IBAction func PianoC(sender: AnyObject) {
       audioPlayer.play() 
   }

}

Latest Swift 4.2 :

   let pianoSound = URL(fileURLWithPath: Bundle.main.path(forResource: "btn_click_sound", ofType: "mp3")!)
   var audioPlayer = AVAudioPlayer()

   @IBAction func PianoC(sender: AnyObject) {
       do {
            audioPlayer = try AVAudioPlayer(contentsOf: pianoSound)
            audioPlayer.play()
       } catch {
          // couldn't load file :(
       } 
   }
4
  • thanks for your answer, i really appreciate. sorry i'm not used to add comment,,, it doesn't work and i replied to you by answering...
    – Bick
    Sep 9, 2014 at 10:56
  • after studying Xcode and Swift for a while and now I understand your answer. It worked! thank you very much!
    – Bick
    Oct 1, 2014 at 8:58
  • 4
    Why are you initializing audioPlayer to AVAudioPlayer()? Sep 16, 2015 at 19:11
  • @jpheldson Yeah, I noticed that too.
    – Robo Robok
    Aug 7, 2017 at 14:36
9

Swift 3

the syntax is now as follows: first add import AVFoundation on top of the code to have access to AVFoundation Framework.

import UIKit
import AVFoundation

class ViewController: UIViewController {
    //this is your audio playback instance
    var audioPlayer = AVAudioPlayer()


    override func viewDidLoad() {
        super.viewDidLoad()
        // address of the music file.
        let music = Bundle.main.path(forResource: "Music", ofType: "mp3")
        // copy this syntax, it tells the compiler what to do when action is received
        do {
            audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: music! ))
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryAmbient)
            try AVAudioSession.sharedInstance().setActive(true)
        }
        catch{
            print(error)
        }

    }
//this runs the do try statement
    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()
    }
}
7

SWIFT 5

import AVFoundation


class Test {
    
    var player: AVAudioPlayer!
    
    func playAudio() {
        
        let url = Bundle.main.url(forResource: "Sound", withExtension: "mp3")
        player = try! AVAudioPlayer(contentsOf: url!)
        player.play()
        
        
    }
    
}
4

In Swift 4:

import AVFoundation
class ViewController: UIViewController, ARSCNViewDelegate, ARSessionDelegate {
    let popSound = Bundle.main.url(forResource: "Pop", withExtension: "mp3")
    var audioPlayer = AVAudioPlayer()

  override func viewDidLoad() {
       do {
            audioPlayer = try AVAudioPlayer(contentsOf: popSound!)
            audioPlayer.play()
        } catch {
            print("couldn't load sound file")
        }
}
2
  • This crashes as it returns nil for popSound. This can be easily fixed using the following code: let popSound = Bundle.main.path(forResource: "pop.mp3", ofType:nil)! audioPlayer = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: popSound))
    – Priyanka
    Aug 31, 2018 at 6:58
  • Please avoid force unwrapping values as it is a dangerous action and may cause unexpected app crashes. Always remember to write as safe as possible code.
    – D. B.
    Feb 19, 2020 at 16:22
3
import UIKit
import AVFoundation

class ViewController: UIViewController {
    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func button1Action(sender: AnyObject) {
        let CatSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("Meow-sounds", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL: CatSound)
            audioPlayer.prepareToPlay()
        } catch {
            print("Problem in getting File")
        }
        audioPlayer.play()
    }
}
3
  • Please don't post similar answers. Anyway, if a question already has an answer available, flag the question as duplicate instead of answering. Thanks.
    – Eric Aya
    Sep 11, 2016 at 11:22
  • @Eric Aya Look at my code.. It is different from above answer.. I use try and catch method for error handling which is necessary in x-code Version 7.1 (7B91b) for new swift Sep 13, 2016 at 10:45
  • I wasn't talking about the answers here. The problem is that you've posted an answer similar to the one you've already posted on the other page. That's why I told you to avoid posting duplicates and to flag the question instead.
    – Eric Aya
    Sep 13, 2016 at 10:48
2

In Swift 4

This worked for me try it out.

import UIKit
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate{

    var audioPlayer = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()
    }



    @IBAction func notePressed(_ sender: UIButton) {

        let soundURL = NSURL(fileURLWithPath: Bundle.main.path(forResource: "note1", ofType: "wav")!)

        do{
            audioPlayer = try AVAudioPlayer(contentsOf: soundURL as URL)

        }catch {
            print("there was some error. The error was \(error)")
        }
        audioPlayer.play()

    }



}
0

In Swift 3:

import UIKit
import AVFoundation

class QuestionView: UIViewController {

    var btnButton = UIButton()
    var player = AVAudioPlayer()

    override func viewDidLoad() {
        super.viewDidLoad()

        btnButton.frame = CGRect(x: 100, y: 100, width: 100, height: 100)
        btnButton.backgroundColor = UIColor.blue
        btnButton.addTarget(self, action: #selector(ButtonSound), for: .touchUpInside)

    }

    func ButtonSound() {

       do {

           //  make sure to add this sound to your project

           let audioPath = Bundle.main.path(forResource: "Click", ofType: "mp3")

           try player = AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!) as URL)


       } catch {

           print("Error !")

       }

       player.play()

    }

}
-1

If you just want a click effect, the code below will work.
The bird file must be in xcode.

self.run(SKAction.playSoundFileNamed("Bird.mp3", waitForCompletion:false))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.