Guy de Bromhead
Guy de Bromhead

Reputation: 31

How to play a sound from an array when tap a button in a collection view cell in Swift 3?

USING iOS SWIFT 3

I have developed a custom keyboard using a collectionView. Each collectionViewCell has a button inside from an array of buttons created in my code - When user taps this button I would like the appropriate sound from the array of sounds also created in my code to play....the arrays are set up so that the array of buttons corresponds directly to the array of sounds for instance

var buttons = ["1", "2", "3", "4"] var sounds = ["sound1", "sound2", "sound3", "sound 4"]

I have managed to get the sounds playing from the array in random order, but I want the sounds to play in order of the array - so when user taps button 1, sound1 will play....when user taps button 2, sound2 will play etc

At the moment on the iOS simulator when user taps button 1, any one of the above sounds is picked at random to play

here is the code I have used when user taps button in collectionViewCell sounds play randomly rather than matching to the order of the "sounds" array. FYI in the below code "Sounds" is the array of sounds I have created

 @IBAction func cellButton(_ sender: AnyObject) {
   let range: UInt32 = UInt32(Sounds.count)
    let number = Int(arc4random_uniform(range))

    self.setupAudioPlayer(file: Sounds[number] as NSString, type: ".m4a")
    self.soundPlayer.play()
}

Upvotes: 0

Views: 715

Answers (0)

Related Questions