0

I know this is an already asked question, but i cant get no answer

i found this way to play the sound:

 Clip sound = AudioSystem.getClip(); sound.open(AudioSystem.getAudioInputStream(new File("path/to/sound"))); sound.start(); 

but the problem is i run this code in a gameloop, and i would like to structure it in a way so that i dont need to read the sound from input each time, but already have saved the sound in the memory so i dont have to load it everytime.

i tried doing something like this:

 Clip sound = AudioSystem.getClip(); sound.open(AudioSystem.getAudioInputStream(new File("path/to/sound"))); while(true) { sound.start(); } 

also like this

AudioStream audiostream = AudioSystem.getAudioInputStream(new File("path/to/sound")); while(true) { Clip sound = AudioSystem.getClip(); sound.open(AudioSystem.getAudioInputStream(audiostream)); sound.start(); } 

but it doesnt work, or it works only 1 time

2
  • 1
    When using a Java core API class, always look at the JavaDocs first. If you still do not get it, go through the Java Sound tutorial. Commented May 18, 2021 at 14:42
  • Please accept the answer as correct or ask a follow-up question. Commented Jan 21, 2023 at 5:37

1 Answer 1

1

Creating an instance variable is a good way to go.

To play the sound again, first set the frame position to the 0th frame or millisecond. The play() method always commences from wherever the sound has been stopped.

Thus:

while(true) { sound.setFramePosition(0); sound.play(); ... } 

Clip (Java SE 15 & JDK 15)

Playback of an audio clip may be started and stopped using the start and stop methods. These methods do not reset the media position; start causes playback to continue from the position where playback was last stopped. To restart playback from the beginning of the clip's audio data, simply follow the invocation of stop with setFramePosition(0), which rewinds the media to the beginning of the clip.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.