简体   繁体   中英

Multi Threading in Java for Audio

I finally figured out how to play audio with java, and enjoyed the implications of it; however, when I wanted to create a music selecting program, one that would include functioning buttons, I realized that my methods of playing the audio would conflict with the rest of the program. When playing the audio, I need to use a Thread.sleep that will last the same length as the audio file, but that prevents me from pausing, choosing a different song, etc. I have not fully completed the main part of my program, as I just started today. I have searched some different websites about multi threading and playing audio in Java, yet none give me a good method of resolving this issue. I wanted to know if it's possible to create a new thread, and then run audio on it at the same time as the original thread, and how I would access one from the other. Thanks

PS Ik this is confusing as frick if clarification and pictures r needed ill send them as needed

Thread.sleep is only used with audio in situation where it is necessary to keep the program from exiting while the audio is playing. If your program is running, doing other things for the duration, there is no need for the sleep command.

When you play a Clip or SourceDataLine , the audio rendering that is called runs on its own thread, but the thread is a daemon thread. A daemon thread, unlike regular threads, will not hold a running Java program open.

I haven't seen the rest of your code, but a good way to demonstrate this to yourself would be to create a simple form with a button. Have the button launch the sound and DON'T include any sleep commands. As long as the form with the button is up and visible, the sound should play through to completion.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM