Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift, how to play sound when press a button

Tags:

swift

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) {
    }
}
like image 569
Bick Avatar asked Sep 09 '14 03:09

Bick


5 Answers

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 :(
       } 
   }
like image 67
gabriel Avatar answered Nov 02 '22 20:11

gabriel


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()
    }
}
like image 24
MiladiuM Avatar answered Nov 02 '22 19:11

MiladiuM


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")
        }
}
like image 25
nanospeck Avatar answered Nov 02 '22 20:11

nanospeck


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()
    }
}
like image 44
Sachin Dobariya Avatar answered Nov 02 '22 19:11

Sachin Dobariya


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()
        
        
    }
    
}
like image 41
Bandyliuk Avatar answered Nov 02 '22 20:11

Bandyliuk