Figure 1 shows the code segment in an example for adding a background sound in our
virtual 3D world. In line 5, the sound file is opened and loaded by a MediaContainer from
the current directory. Alternatively, a path can be specified or the sound data can come
from the Internet through a URL such as http://vlab.ee.nus.edu.sg/vlab/sound.wav.
Lines 8 to 17 declare some reading and writing capabilities to the sound node created
in Line 1. With these capabilities set, it is now possible to change the sound data and alter
the enable, loop, release and continuous play functionality of the node through some of
the methods in lines 18 to 25.
Specifically, line 18 uses the setSoundData method to change the sound source to cor-
respond to that loaded earlier. Line 19 sets the initial amplitude gain for playing the sound,
line 20 uses the setLoop method to specify number of times that sound will be repeated.
In the current case, the argument is 0 and the sound will be played once. An argument of
-1 will repeat the sound indefinitely.
Line 21 sets the setReleaseEnable flag to false. This flag is only valid when the sound
is played once. Setting this flag to true will force the sound to be played until it finishes
even in the presence of a stop request.
Similarly, line 22 set the setContinuousEnable flag to false. Setting this to true gives rise
to the effect that the sound will be played continuously in a silent mode even if the node is
no longer active as when it is outside the scheduling bound. A false setting will play the
sound from the beginning when the audio object reenters the scheduling bound.
Changing the setEnable flag in line 23 is similar to pressing the play or stop button
in an audio system. A true will play the sound, while a false will stop it. Essentially, it is
straightforward to set up and use sound in Java 3D. We just need to create an audio object,
load the sound track to a MediaContainer, link the MediaContainer to the audio object,
enable the latter, and set the scheduling bound.
With BackgroundSound being similar to ambient light, PointSound, another subclass of
Sound, is similar to point light. Essentially, as illustrated in Figure 2, a point sound source
has a spatial location and generates sound that radiates uniformly in all directions from
that location. However, the amplitude of the sound will decrease as it travels further and
further away from the source.
To realize this attenuation characteristic, an array of points giving the system gains at
different distances from the source can be specified. This will enable Java 3D to interpolate
the gain at other distance in a linear manner. In the example code segment in Figure 2 for
the creation of a point sound source, line 3 specifies that the gain on the amplitude will still
be 1 at a short distance of 1 from the source, but will decrease to 0.5 at a distance of 5. At
a further distance of 10, the gain becomes 0 or that the sound will become silent.
Search WWH ::