iOS Tutorials: Play Sound

OVERVIEW

We will be creating a project here by using seven buttons in which when clicked upon will play a sound. The protocol here being used is AVAudioPlayerDelegate. We hope to create a mini piano.

Before proceeding, download the sound files¬†here. Let’s try to achieve several things by looking at the picture below.

  1. Create a folder where you could store all the downloaded musics file in.
  2. Create your Main.storyboard by using buttons and assigning whatever color you like.
  3. Assign a tag for each button.

Once completed, there are several things that needs to be done below:

  1. import AVFoundation
  2. use AVAudioPlayerDelegate protocol
  3. create a player variable that inherits the AVAudioPlayer functionality
  4. create a selected variable to keep track of the button selected
  5. create an array that stores the music files with the same file name
  6. create a function that play sound
import AVFoundation

class ViewController: UIViewController, AVAudioPlayerDelegate {
    var player: AVAudioPlayer!
    var selected: String = ""
    let sounds = ["note1","note2","note3","note4","note5","note6","note7"]

 func playSound(){
        let url = Bundle.main.url(forResource: selected, withExtension: "wav")
        do {
            player = try AVAudioPlayer(contentsOf: url!)
        } catch {
            print(error)
        }
        player.play()
    }

Our one last step is to configure the IBAction button where we will be creating an IBAction by linking all those buttons to the same IBAction as shown below. Note that the sender is taking UIButton parameter. With this IBAction, we are keeping track of each button selected and play according to the button selected.

@IBAction func notePressed(_ sender: UIButton) {
    selected = sounds[sender.tag]
    playSound()
}

And now, you should have a working mini piano.

Check out the code uploaded to GitHub

  • Article By :
    Founder of DaddyCoding. Studied Computer Science, Information System and Information Technology at BYU-Hawaii. Currently spending most of my time researching and learning on helping to expose making iOS apps.

Random Posts

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*