Hey again. So I was looking around on how to play sounds through Java via Google and I couldn’t many easy to comprehend explanations. There is a lot more to it than is presented here, but for simple play back of a sound file with no “fancy” stuff this is the way to do it.
First an explanation, then the code.
Playing a sound file is actually rather easy, thanks to the Clip class. First thing you do is create an AudioInputStream from a file, of course this file is YOUR audio file. I just have a constant
clip_loc pointing to its location on disk. NOTE: You can also use a URL instead of a file.
After we have our AudioInputStream, we create our clip. We use getClip() from the AudioSystem class, then open our AudioInputStream for the clip, then just use the clips start() method to play it. It’s that simple!
After that we have a set of empty while loops. These loops just serve to block execution while the clip is playing. ie. keep the program open until the clip finishes playing. If your program will stay open anyways, then you will want to remove these lines and place the clip’s close() method in an appropriate place.
After the loops, the clip closes to release resources and we’re done! That simple.
Also, you’ll notice the entire code was wrapped in a try statement. Feel free to throw the exceptions instead. Also, I used a generalized catch to handle all the Exceptions. This is not good practice, but it made the code simpler. Really you’d want to catch each exception and handle it individually.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31