Hello,
I´m developing a simple piano on unity that will play the sound corresponding to the keys the user touches. I´m new to managing sounds in unity and currently all I know is I can play a sound using the audioclip.play()
However I would like to be able to play chords, which means I have to play multiple sound at the same time. Can anyone tell me how can I accomplish this?
Your original question was honestly too easily researched to have passed moderation, but you raise a really interesting topic which I can address. I edited your question so others might find this explanation.
Not sure if there’s anything new in Unity 5 regarding this. In previous versions, the answer to playing concurrent sounds is definitely:
Use multiple audio sources. You need one AudioSource component for each concurrent sound you want to play.
When they build keyboards (at least in the sub-thousand-dollar range) they have perhaps two dozen samples of each instrument at various keys. When the pianist hits a key, the “nearest” sample is played with an adjusted pitch which corresponds to that key. (High quality keyboards probably use individual samples per key or at least use more sophisticated methods).
I’ve actually done this before in Unity - not a piano, but playing instrument samples at a specific pitch. It works just fine. There’s a formula for determining how much the pitch needs to change to achieve a certain key. If you know the key of your sample, you can arrive at any “nearby” key and maintain a good natural sound. I don’t remember the formula, but it was easy to find.
So your piano or whatever you expose to the user could be as complex or simple as you like, but if it were me, I’d have a manager class which responds to key presses in the following way:
A key, when pressed, requests a note be played at its corresponding pitch.
The script responsible accepts this pitch information and creates an AudioSource from a prefab.
The prefab gets loaded with the nearest sample, and corrected for pitch.
The sample is played until the key is released or it attenuates naturally…
…at which point you can destroy or recycle the prefab instance.
There’s a lot of wiggle room with how you handle this. It can be as complex as you like, but this is the simplest, cleanest approach I can think of.
Best,