我能够使代码正常工作,现在对Clips有了更好的了解。该页面对我帮助最大的页面是http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html,它分解了所有内容,并帮助我查看了哪里出错了。这是我的最终工作代码。和以前一样,如果您看到任何可怕的错误或逻辑或样式方面的问题,请告诉我。
import java.io.File;import java.io.IOException;import java.net.MalformedURLException;import javax.sound.sampled.AudioInputStream;import javax.sound.sampled.AudioSystem;import javax.sound.sampled.Clip;import javax.sound.sampled.LineUnavailableException;import javax.sound.sampled.UnsupportedAudioFileException;public class Sound { private Clip clip; public Sound(String fileName) { // specify the sound to play // (assuming the sound can be played by the audio system) // from a wave File try { File file = new File(fileName); if (file.exists()) { AudioInputStream sound = AudioSystem.getAudioInputStream(file); // load the sound into memory (a Clip) clip = AudioSystem.getClip(); clip.open(sound); } else { throw new RuntimeException("Sound: file not found: " + fileName); } } catch (MalformedURLException e) { e.printStackTrace(); throw new RuntimeException("Sound: Malformed URL: " + e); } catch (UnsupportedAudioFileException e) { e.printStackTrace(); throw new RuntimeException("Sound: Unsupported Audio File: " + e); } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Sound: Input/Output Error: " + e); } catch (LineUnavailableException e) { e.printStackTrace(); throw new RuntimeException("Sound: Line Unavailable Exception Error: " + e); } // play, stop, loop the sound clip } public void play(){ clip.setframePosition(0); // Must always rewind! clip.start(); } public void loop(){ clip.loop(Clip.LOOP_CONTINUOUSLY); } public void stop(){ clip.stop(); } }


