2012-08-12 61 views
6

我試圖在遊戲過程中一次播放兩個wav聲音(背景音樂和效果)。我首先使用java中的另一個音頻處理程序構建了這段代碼,它將處理播放,停止和循環聲音。這種構造會一次播放背景音樂或效果,但只能播放一種。我環顧了互聯網,並被告知使用javax.sound.sampled.Clip處理聲音,以便重複使用相同的構造(播放,停止,循環),但將其切換爲使用javax.sound.sampled.Clip。現在我完全失去了。從我迄今爲止讀過的內容中,我已經完成了所有的事情,並且在eclipse編輯器中沒有發現任何錯誤,但是當我運行它時,我得到了兩個錯誤之一。在eclipse中(在Linux上運行)拋出一個LineUnavailableException。在eclipse中(在Windows 7上運行),我在此代碼的loop()部分中得到一個java.lang.NullPointerException。如果你能告訴我我做錯了什麼,或者指向我一些相關的文檔,我會很感激。我假設它的代碼處理異常,但我不確定。如果你看到任何其他可怕的代碼失誤,請讓我知道我努力成爲最好的程序員,我真的很感激建設性的批評。感謝您的時間。使用javax.sound.sampled.Clip播放,循環並停止遊戲中的多個聲音。意外錯誤

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; 

    /** 
    * Handles play, pause, and looping of sounds for the game. 
    * @author Tyler Thomas 
    * 
    */ 
    public class Sound { 
     private Clip myClip; 
     public Sound(String fileName) { 
       try { 
        File file = new File(fileName); 
        if (file.exists()) { 
         Clip myClip = AudioSystem.getClip(); 
         AudioInputStream ais = AudioSystem.getAudioInputStream(file.toURI().toURL()); 
         myClip.open(ais); 
        } 
        else { 
         throw new RuntimeException("Sound: file not found: " + fileName); 
        } 
       } 
       catch (MalformedURLException e) { 
        throw new RuntimeException("Sound: Malformed URL: " + e); 
       } 
       catch (UnsupportedAudioFileException e) { 
        throw new RuntimeException("Sound: Unsupported Audio File: " + e); 
       } 
       catch (IOException e) { 
        throw new RuntimeException("Sound: Input/Output Error: " + e); 
       } 
       catch (LineUnavailableException e) { 
        throw new RuntimeException("Sound: Line Unavailable: " + e); 
       } 
     } 
     public void play(){ 
      myClip.setFramePosition(0); // Must always rewind! 
      myClip.loop(0); 
      myClip.start(); 
     } 
     public void loop(){ 
      myClip.loop(Clip.LOOP_CONTINUOUSLY); 
     } 
     public void stop(){ 
      myClip.stop(); 
     } 
    } 

回答

12

我能夠使代碼工作,現在有更好的理解剪輯。幫助我最多的頁面是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; 

/** 
* Handles playing, stoping, and looping of sounds for the game. 
* @author Tyler Thomas 
* 
*/ 
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(); 
     } 
    } 
2

我發現了一種有用的技術來阻止聲音。你可以複製這兩個類並自己測試。不過,clip.stop()方法更多的是一種暫停方法。它停止播放聲音,是的,但它不能清除線路中的聲音。結果,聲音仍在排隊等待播放,並且不能播放新聲音。因此,使用clip.close()方法將清除排隊的數據,並允許播放新的聲音或執行其他操作。另外請注意,在下面的代碼中,聲音文件被放置在名爲「predator.wav」的項目文件夾中,該聲音可以是您想要使用的任何類型的聲音,而不是我選擇的聲音,但請確保它是.wav格式,並且聲音必須位於項目文件夾的最頂層。

/* 
* File: KeyMap.java 
* Author: Andrew Peturis Chaselyn Langley; UAB EE Students 
* Assignment: SoundBox - EE333 Fall 2015 
* Vers: 1.0.0 10/20/2015 agp - initial coding 
* 
* Credits: Dr. Green, UAB EE Engineering Professor 
*/ 

import java.io.File; 
import java.io.IOException; 
import javax.sound.sampled.AudioSystem; 
import javax.sound.sampled.Clip; 
import javax.sound.sampled.LineUnavailableException; 
import javax.sound.sampled.UnsupportedAudioFileException; 

public class KeyMap { 

    private char keyCode; 
    private String song; 
    private Clip clip; 

    // Don't allow default constructor 
    private KeyMap() { 
    } 

    public KeyMap(char keyCode, String song) throws LineUnavailableException { 
     this.keyCode = keyCode; 
     this.song = song; 

     // Create an audiostream from the inputstream 
     clip = AudioSystem.getClip(); 
    } 

    public boolean match(char key) { 
     return key == keyCode; 
    } 

    // Play a sound using javax.sound and Clip interface 
    public String play() { 
     try { 
      // Open a sound file stored in the project folder 
      clip.open(AudioSystem.getAudioInputStream(new File(song + ".wav"))); 

      // Play the audio clip with the audioplayer class 
      clip.start(); 

      // Create a sleep time of 2 seconds to prevent any action from occuring for the first 
      // 2 seconds of the sound playing 
      Thread.sleep(2000); 

     } catch (LineUnavailableException | UnsupportedAudioFileException | IOException | InterruptedException e) { 
      System.out.println("Things did not go well"); 
      System.exit(-1); 
     } 
     return song; 
    } 

    // Stop a sound from playing and clear out the line to play another sound if need be. 
    public void stop() { 
     // clip.stop() will only pause the sound and still leave the sound in the line 
     // waiting to be continued. It does not actually clear the line so a new action could be performed. 
     clip.stop(); 

     // clip.close(); will clear out the line and allow a new sound to play. clip.flush() was not 
     // used because it can only flush out a line of data already performed. 
     clip.close(); 
    } 
} 

/* 
* File: SoundBox.java 
* Author: Andrew Peturis, Chaselyn Langley; UAB EE Students 
* Assignment: GUI SoundBox - EE333 Fall 2015 
* Vers: 1.0.0 09/08/2015 agp - initial coding 
*/ 

import java.io.BufferedReader; 
import java.io.IOException; 
import java.io.InputStream; 
import java.io.InputStreamReader; 
import java.util.Scanner; 
import javax.sound.sampled.LineUnavailableException; 

/** 
* 
* @author Andrew Peturis, Chaselyn Langley 
* 
*/ 
public class SoundBox { 

    static Scanner scanner = new Scanner(System.in); //Scanner object to read user input 
    InputStream input; 

    /** 
    * @param args the command line arguments 
    * @throws java.io.IOException 
    */ 
    public static void main(String[] args) throws IOException, LineUnavailableException { 

     String line; 
     Character firstChar; 
     String predator = "predator"; 
     String explosion = "explosion"; 

     BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); 

     KeyMap[] keyedSongs = { 
      new KeyMap('a', predator),}; 

     while (true) { 
      line = br.readLine(); 
      firstChar = line.charAt(0); 

      for (int i = 0; i < keyedSongs.length; i++) { 
       if (keyedSongs[i].match(firstChar)) { 

        // Notice now by running the code, after the first second of sleep time the sound can 
        // and another sound can be played in its place 
        keyedSongs[i].stop(); 
        System.out.println("Played the sound: " + keyedSongs[i].play()); 
        break; 
       } 
      } 

      if (firstChar == 'q') { 
       break; 
      } 
     } 
    } 
}