Play sound and opacity

import UIKit

import AVFoundation

class ViewController: UIViewController {

        var player: AVAudioPlayer!

        override func viewDidLoad() {

        super.viewDidLoad()

    }

        @IBAction func keyPressed(_ sender: UIButton) {

                playSound(soundname: sender.currentTitle!)

  //Set sender's opacity to half 

        sender.alpha = 0.5

        DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {

            //Bring's sender's opacity back up to fully opaque after 0.2 seconds.

            sender.alpha = 1.0

        }

            //Function to play sound    

        func playSound(soundname: String) {

            let url = Bundle.main.url(forResource: soundname, withExtension: "wav")

            player = try! AVAudioPlayer(contentsOf: url!)

            player.play()

                    }

                    }

}




@IBAction func keyPressed(_:):
  • This is an IBAction function, meaning it is connected to a user interface element (like a UIButton) in Interface Builder. It gets triggered when the connected button is pressed.
  • The sender parameter represents the UIButton that triggered the action.


playSound(soundname:):
  • This function is called from the keyPressed function to play a sound.
  • It takes a soundname parameter, which is the title of the UIButton that was pressed (assuming the button's title corresponds to the name of the sound file).


Loading and Playing the Sound
:
  • Bundle.main.url(forResource:withExtension:) is used to get the URL of the sound file (assumed to be a WAV file) based on the provided soundname.
  • An AVAudioPlayer instance is created using the obtained URL.
  • try! is used to force-unwrap the result of AVAudioPlayer(contentsOf:). This is assuming that the sound file exists, and the URL is valid. In a production app, you might want to handle errors more gracefully.
  • The play() method is then called on the AVAudioPlayer instance to play the sound.

Comments