w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Swift, how to play sound when press a button

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

}




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.