Keita Bick Ohshiro Keita Bick Ohshiro - 2 months ago 11
Swift Question

Swift, how to play sound when press a button

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"

Thanks in advance.

import UIKit

class ViewController: UIViewController {

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

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

@IBAction func PianoC(sender: AnyObject) {
}

}

Answer

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

}