I have MP3 Files that I’ve added to an XoJo project and named them R0 through R21. I want to randomly play one of the sounds.
The following code chooses the random number and then forms the name of the sound I want to play in a string. How do I create an object using the name in in the string “MySound” that I can then use the ObjectName.Play and have it play that sound?
Hi Jason, thanks for the info on Dictionaries. From what I can see, with the simple app I’m working on, Dictionaries will actually require more code and make it a bit more complicated since I need a dictionary entry for each sound file. Then I need the code to access each item. For this situation, an if then statement is much more straightforward and less code. I was hoping for something that could make a decision based on the MyString contents and some how cast that to that correct format to use .play. That would reduce the amount of code.
I will certainly learn about using Dictionaries for future use!
The short answer is, no, you cannot get the Xojo object directly from a string. It might actually be better to have the sound files in your resources folder and access them from there, rather than dragging them into your project.
After you add the setup in an open event, accessing a dictionary entry is very easy: Example I typed into the forum:
// in a window, module, app property:
var mySoundDictionary as Dictionary
// in open event
mySoundDictionary = new Dictionary
mySoundDictionary.value("R0") = R0
mySoundDictionary.value("R1") = R1
// etc ...
mySoundDictionary.value("R21") = R21
// when accessing sound to play
i = System.Random.Inrange(0,21)
lbl_result.value = aResponse(i)
MySoundString = “R” + i.tostring
MySound = mySoundDictionary.value(MySoundString)
MySound.Play()
Yes, sound.open() can open mp3 files. Check your Resources file in your build folder, the mp3 files might already be there since you dragged them in to the project.