2012-08-12 5 views
6

Ich versuche, zwei WAV-Sounds gleichzeitig zu spielen (Hintergrundmusik und ein Effekt). Ich habe diesen Codeabschnitt zuerst mit einem anderen Audio-Handler in Java erstellt, der das Abspielen, Stoppen und Looping des Sounds übernimmt. Dieses Konstrukt würde die Hintergrundmusik oder den Hintergrundeffekt spielen, aber nur jeweils einzeln. Ich schaute mich im Internet um und wurde gebeten, javax.sound.sampled.Clip zu verwenden, um die Sounds zu behandeln, so dass das gleiche Konstrukt (play, stop, loop) wiederverwendet wurde, aber es wurde javax.sound.sampled.Clip verwendet. Jetzt bin ich völlig verloren. Von dem, was ich bisher gelesen habe, habe ich alles richtig gemacht und bekomme keine Fehler im Eclipse-Editor, aber wenn ich es ausführe, erhalte ich einen von zwei Fehlern. In Eclipse (unter Linux) wird eine LineUnavailableException ausgelöst. In Eclipse (läuft unter Windows 7) bekomme ich eine java.lang.NullPointerException im Abschnitt loop() dieses Codes. Wenn Sie mir zeigen könnten, was ich falsch mache oder auf relevante Dokumente verweisen, würde ich es begrüßen. Ich nehme an, es ist etwas mit meinem Code, der Ausnahmen behandelt, aber ich bin mir nicht sicher. Wenn Sie irgendwelche anderen scheußlichen Code-Fehltritte sehen, lassen Sie es mich bitte wissen. Ich bemühe mich, der beste Programmierer zu sein, den ich kann, und schätze wirklich konstruktive Kritik. Vielen Dank für Ihre Zeit.Verwenden Sie javax.sound.sampled.Clip, um mehrere Sounds in einem Spiel zu spielen, zu loopen und zu stoppen. Unerwartete Fehler

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(); 
     } 
    } 

Antwort

12

Ich konnte den Code arbeiten und jetzt ein besseres Verständnis von Clips haben. Die Seite, die mir am meisten geholfen hat, war http://www3.ntu.edu.sg/home/ehchua/programming/java/J8c_PlayingSound.html, sie unterbricht alles und half mir zu sehen, wo ich Fehler gemacht habe. Hier ist mein abschließender Arbeitscode. Wie immer, wenn Sie irgendwelche schrecklichen Fehler oder über Sehenswürdigkeiten in Logik oder Stil sehen, lassen Sie es mich wissen.

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

Ich fand eine nützliche Technik, um Ton zu stoppen. Sie können diese beiden Klassen kopieren und selbst testen. Dennoch ist die clip.stop() Methode eher eine Pausenmethode. Es stoppt den Klang vom Spielen, ja, aber es löscht nicht den Ton von der Linie. Daher befindet sich der Sound immer noch in der Warteschlange und kein neuer Sound kann wiedergegeben werden. Mit der Methode clip.close() werden diese Daten in der Warteschlange gelöscht und es kann ein neuer Sound abgespielt oder eine andere Aktion ausgeführt werden. Beachten Sie auch, dass im folgenden Code eine Audiodatei im Projektordner namens "predator.wav" gespeichert wurde. Dieser Sound kann jede Art von Sound sein, den Sie anstelle des von mir gewählten Sounds verwenden möchten, aber stellen Sie sicher, dass es ein .wav-Format ist Der Sound muss sich in der obersten Ebene des Projektordners befinden.

/* 
* 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; 
      } 
     } 
    } 
} 
Verwandte Themen