Search code examples
arraysswiftstringavaudioplayer

Error: Cannot convert value of type "[String]" to expected argument type "String?"


Refer to this image please!Help! Can anyone help me understand this error. This is a creative project, in this particular function for my class, I am attempting to create an array of sounds (.wav format). Each sound that is being played corresponds to a letter from a txt file. Four different letters correspond to four different sounds. My program reads each letter from the txt file and identifies which sound to play. My goal is have the sounds overlap because when they are being played, they cut each other off. In order to do this, it is to my understanding that I first need to create an array of sounds, add the array, make the audio player the deligate for each sound/letter it corresponds to, delete the audioPlayer in that array after it finishes playing, then add another array to the one that just finished playing, then remove the array after it finishes playing. I have to do this all while creating a string of sounds. I'm also having a hard time grasping the difference between an array and a string.

   func playSound() {

    let sound: [String] = ["Keys1.wav", "Keys2.wav", "Keys3.wav", "Keys4.wav"]


    if let audioPath = Bundle.main.path(forResource: "Keys1", ofType: "wav") {
    do {
        sound = try AVAudioPlayer(contentsOf: URL(fileURLWithPath: audioPath!))
        activeSound.delegate = self
        Swift.print("Audio was loaded")

    }
    catch {
        Swift.print("Can't read audio file")
        debug(error.localizedDescription)
    }
    }

}

Solution

  • Should be simple. You need to iterate on the array and process each item separately.

    let sounds = [ /* the contents of your array */ ]
    
    for s in sounds {
        // do stuff on s
    }