Thursday, May 5, 2016

Add And Play Sound In Your iOS Project


Tutorial on adding sounds to iOS projects.
  1. Drag and drop your sound file into your project.
    In this example the name of my sound file is "ButtonClickSound.wav".
  2. Code
    import UIKit
    import AVFoundation
    
    class ViewController: UIViewController {
    
        var buttonClickSound: AVAudioPlayer!
        
        override func viewDidLoad() {
            super.viewDidLoad()
            
            let path = NSBundle.mainBundle().pathForResource("ButtonClickSound", 
                ofType: "wav")
            let url = NSURL(fileURLWithPath: path!)
            
            do {
                try buttonClickSound = AVAudioPlayer(contentsOfURL: url)
                buttonClickSound.prepareToPlay()
            } catch let err as NSError {
                print(err.debugDescription)
            }
        }
    
        @IBAction func PlaySound_TouchUpInside(sender: UIButton) {
            if buttonClickSound.playing {
                buttonClickSound.stop()
            }
    
            buttonClickSound.play()
        }
    }
    
    

(Swift 2.2)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...