Pregunta

In Turbo C++ we have a header file called dos.h which exposes three functions sound, nosound and delay. Using these three functions it was possible to write a rudimentary piano program in C++.

I wanted to achieve the same result using Java. My options were either to use the library provided by jfugue or javax.sound.sampled. The problem is that I don't know the duration each note is played beforehand.

I want to start playing a certain frequency when the user presses a certain key and stop only when the user releases it. How may I tackle this problem?

¿Fue útil?

Solución

The Java tutorials have an example where a boolean is consulted in the innermost while loop where one is packaging the bytes and handing them off to the SourceDataLine for playback.

Thus, your event, perhaps a key-off event, can be written to change this boolean. Since the sound playback is in its own thread, it is good to make the boolean "volatile", and to use this method of messaging rather than trying to directly control the playback.

Let's see if I can find the tutorial example... http://docs.oracle.com/javase/tutorial/sound/playing.html

Notice in the example in the section "Using a Source Data Line" there is a while loop with the expression "!stopped" as one of the conditions. The base class for the playback in this example most certainly has a boolean "stopped", and probably has it marked "volatile".

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top