Select SFX to Play in Audio Player?

Hi Apple Dev Community,
Is there an easy way to select a SFX or music to play for a specific audio player instance in Swift?
You see, in pretty much every other language I have learned, you can do something like

audioPlayer.play("mySoundEffect.wav");
audioPlayer.play("anotherSoundEffect.wav");


where the argument for .play( ) is simply the URL or the file name of the audio file.


However, no matter how many articles I read or tutorials I watch, no where can I find an equivalent for Swift...


In Swift, you instantiate an audio player by calling

audioPlayer = try AVAudioPlayer(contentsOf: URL.init(Bundle.main.path(forResource: "mySoundEffect", ofType: "wav")!))


and then play the audio by calling

audioPlayer.play()

with no arguments.
Does this mean that, if I have multiple sound effects I want to sample from, I have to create an audio player instance for each one of them?
What if I have over 100+ sound effects in my game app? Will I then have to create 100+ instances of audio player?

Replies

Seems you have experienced 100+ other languages saying pretty much.


In Swift, you instantiate an audio player by calling

audioPlayer = try AVAudioPlayer(contentsOf: URL.init(Bundle.main.path(forResource: "mySoundEffect", ofType: "wav")!)) 

Why do you dare to write the code in such a bad manner?


audioPlayer = try AVAudioPlayer(contentsOf: Bundle.main.url(forResource: "mySoundEffect", withExtension: "wav")!)


What if I have over 100+ sound effects in my game app? Will I then have to create 100+ instances of audio player?

That's one way to get better response. Another way, you can replace the instance at each time you need.


If you think Apple's frameworks are not designed as they should be, you can write a feature request through the bug reporter.