Wow!!.. Just gets better… Just tried Repton.midi (my favourite 80s BBC B game)… Came out pretty well…
Unfortunately unable to post (as it exceeds the 10,000 characters limit).
I working on my own sync engine. It works well so far but I only a single sin wave for the sound. I want to add more diversity in the sound (my knowledge in this field is low).
I don’t really get how ShannonSmith proced. And I don’t get the :
double sin4 = (Math.sin(Math.PI*frequency*time*8.0));
double sin6 = (Math.sin(Math.PI*frequency*time*12.0));
It is not supposed to be frequency/8.0 and frequency/12.0 for harmonics ?
My main problem is to understand how to make a collection parameters to deal with different instruments…
That code is from Alan_W’s not mine. Frequency/8 would give you sub-harmonics (below the fundamental). Also I wouldn’t recommend recalculating the phase of the oscillator every sample from the time, it means you have to use doubles and things tend to drift.
Writing good sounding synthesizers is actually a very involved topic and takes a lot of effort. If you want a slightly richer sound than a sine wave there is a simple technique that yields some nice sounds. I used it in my synth, basically you frequency modulate a sine oscillator with itself. This produces something very close to a saw wave.
Here is how:
float phase = 0.0f; // the phase of the oscillator (goes from 0 -> 1)
float lastOut = 0.0f; // the last output of the oscillator so we can feed back in for some nice sounds.
float feedbackAmount = 2.0f; // the amount of feedback, controls the buzzyness of the oscillator.
float frequency = 440.0f; // the frequency of our tone.
for(every sample){
float output = (float)Math.sin(phase*Math.PI*2.0 + lastOut*feedbackAmount);
phase += freq/SAMPLE_RATE; // increment the phase (SAMPLE_RATE is probably 44100)
if(phase > 1.0f){
phase -= 1.0f; // wrap the phase when it goes over 1.0f
}
lastOut = (output + lastOut)*0.5f; // filter and store the output, the filter is necessary for good results
}
Thats it, just increase the feedbackAmount for a more rich/buzzy sound. If you want even better sounds change the feedbackAmount over time or stack several oscillators slightly detuned together.
You might want to try removing the Thread.sleep, and instead just use the sourceDataLine.write() call. That’s guaranteed to wait until there’s free space available on the buffer.
I added the “meat” from this thread to the Wiki: http://wiki.games4j.com/wiki/en/Java_4K_competition#Sound
Would be really cool if you could add some info on how to tune the code for own setup. For example how to create different sounds and how the tunes are composed. Update the wiki as you see right.
@Allan_W: I just copied you code to the wiki, since it was here in the open. Just remove it from the wiki if you have anything against it. I hope that eventually people will move it to the wiki by them selves, but helping along for right now.