2009-03-15 5 views
3

Fondamentalement, j'essaie d'utiliser cette classe SoundEffect dans un jeu java simple sur lequel je travaille pour mon devoir.Utilisation d'effets sonores dans un jeu java

import java.io.*; 
import java.net.URL; 
import javax.sound.sampled.*; 

/** 
* This enum encapsulates all the sound effects of a game, so as to separate the sound playing 
* codes from the game codes. 
* 1. Define all your sound effect names and the associated wave file. 
* 2. To play a specific sound, simply invoke SoundEffect.SOUND_NAME.play(). 
* 3. You might optionally invoke the static method SoundEffect.init() to pre-load all the 
* sound files, so that the play is not paused while loading the file for the first time. 
* 4. You can use the static variable SoundEffect.volume to mute the sound. 
*/ 
public enum SoundEffect { 
    EAT("eat.wav"), // explosion 
    GONG("gong.wav"),   // gong 
    SHOOT("shoot.wav");  // bullet 

    // Nested class for specifying volume 
    public static enum Volume { 
     MUTE, LOW, MEDIUM, HIGH 
    } 

    public static Volume volume = Volume.LOW; 

    // Each sound effect has its own clip, loaded with its own sound file. 
    private Clip clip; 

    // Constructor to construct each element of the enum with its own sound file. 
    SoundEffect(String soundFileName) { 
     try { 
     // Use URL (instead of File) to read from disk and JAR. 
     URL url = this.getClass().getClassLoader().getResource(soundFileName); 
     // Set up an audio input stream piped from the sound file. 
     AudioInputStream audioInputStream = AudioSystem.getAudioInputStream(url); 
     // Get a clip resource. 
     clip = AudioSystem.getClip(); 
     // Open audio clip and load samples from the audio input stream. 
     clip.open(audioInputStream); 
     } catch (UnsupportedAudioFileException e) { 
     e.printStackTrace(); 
     } catch (IOException e) { 
     e.printStackTrace(); 
     } catch (LineUnavailableException e) { 
     e.printStackTrace(); 
     } 
    } 

    // Play or Re-play the sound effect from the beginning, by rewinding. 
    public void play() { 
     if (volume != Volume.MUTE) { 
     if (clip.isRunning()) 
      clip.stop(); // Stop the player if it is still running 
     clip.setFramePosition(0); // rewind to the beginning 
     clip.start();  // Start playing 
     } 
    } 

    // Optional static method to pre-load all the sound files. 
    static void init() { 
     values(); // calls the constructor for all the elements 
    } 
} 

Voici une implémentation du son EAT dans la récompense de mon jeu CLASS-

public void react(CollisionEvent e) 
    { 
     Player player = game.getPlayer(); 
     if (e.contact.involves(player)) { 
      player.changePlayerImageEAT(); 
      SoundEffect.EAT.play(); 
      player.addPoint(); 
      System.out.println("Player now has: "+player.getPoints()+ " points."); 
      game.getCurrentLevel().getWorld().remove(this); 
     } 
    } 

Cela devrait jouer le son EAT quand le joueur entre en contact avec une récompense dans mon jeu.

Cependant, quand mon joueur entre en collision avec une récompense, je reçois les erreurs suivantes dans le Terminal-

javax.sound.sampled.LineUnavailableException: ligne avec le format ALAW 8000,0 Hz, 8 bits , chaîne hi-fi , 2 octets/image, pas pris en charge. à com.sun.media.sound.DirectAudioDevice $ DirectDL.implOpen (DirectAudioDevice.java:494) à com.sun.media.sound.DirectAudioDevice $ DirectClip.implOpen (DirectAudioDevice.java:1280) à com. sun.media.sound.AbstractDataLine.open (AbstractDataLine.java:107) at com.sun.media.sound.DirectAudioDevice $ DirectClip.open (DirectAudioDevice.java:1061) at com.sun.media.sound. DirectAudioDevice $ DirectClip.open (DirectAudioDevice.java:1151) à Sonore. (SoundEffect.java:39) à Sonore. (SoundEffect.java:15) à Reward.react (Reward.java:41) à city.soi.platform.World.despatchCollisionEvents (World.java:425) à city.soi.platform.World.step (World.java:608) à city.soi.platform.World.access 000 $ (World.java:42) à city.soi.platform.World $ 1.actionPerformed (World.java:756) à javax.swing.Timer.fireActionPerformed (Timer.java:271) à javax.swing. minuterie $ DoPostEvent.run (Timer.java:201) à java.awt.event.InvocationEvent.dispatch (InvocationEvent.java:209) à java.awt.EventQueue.dispatchEvent (EventQueue.java:597) à java.awt.EventDispatchThread.pumpOneEventForFilters (EventDispatchThread.java:269) à java.awt.EventDispatchThread.pumpEventsForFilter (EventDispatchThread.java:184) à java.awt.EventDispatchThread.pumpEventsForHierarchy (EventDispatchThread.java:174) à java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java:169) à java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java:161) à java.awt.EventDispatchThread.run (EventDispatchThread.java:122) Exception dans le fil "AWT-EventQueue-0" java.lang.ExceptionInInitializerError at Reward.react (Reward.java:41) at city.soi.platform.World.despatchCollisionEvents (World.java:425) à city.soi.platform.World.step (World.java:608) à city.soi.platform.World.access 000 $ (World.java:42) à city.soi.platform.World $ 1.actionPerformed (World.java:756) à javax.swing.Timer.fireActionPerformed (Minuteur.java: 271) à javax.swing.Timer $ DoPostEvent.run (Timer.java:201) à java.awt.event.InvocationEvent.dispatch (InvocationEvent.java:209) à java.awt.EventQueue .dispatchEvent (EventQueue.java:597) à java.awt.EventDispatchThread.pumpOneEventForFilters (EventDispatchThread.java:269) à java.awt.EventDispatchThread.pumpEventsForFilter (EventDispatchThread.java:184) à java.awt. EventDispatchThread.pumpEventsForHierarchy (EventDispatchThread.java:174) at java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java:169) à java.awt.EventDispatchThread.pumpEvents (EventDispatchThread.java:161) à java.awt.EventDispatchThread.run (EventDispatchThread.java:122) causés par: java.lang.NullPointerException à com.sun. media.sound.WaveFileReader.getAudioInputStream (WaveFileReader.java:180) à javax.sound.sampled.AudioSystem.getAudioInputStream (AudioSystem.java:1128) à SoundEffect. (SoundEffect.java:35) à SoundEffect. (SoundEffect.java:16) ... 15 plus

Je n'arrive pas à comprendre ce qui ne va pas. Je suppose que cela a quelque chose à voir avec mes fichiers audio (WAV) n'étant pas supportés. Cependant, peu importe combien de façons je les convertis, ils ne fonctionnent toujours pas.

Ce serait vraiment utile si quelqu'un peut m'éclairer sur ce qui pourrait être mauvais et comment je peux résoudre ce problème.

Exemple de code et toutes les modifications que vous pouvez offrir pour aider à faire fonctionner ce code seront grandement appréciés.

Merci.

Répondre

5

Votre exception est la cause racine

javax.sound.sampled.LineUnavailableException: 
line with format ALAW 8000.0 Hz, 8 bit, stereo, 2 bytes/frame, not supported 

Cela se produit parce que tous les pilotes son pour tous les débits ou codages, ou parce que la machine ne fonctionne tout simplement pas une carte son. Le son peut être codé en A law ou mu law (ou d'autres, tels que MP3) et peut être codé à différents débits et tailles d'échantillons. Java ne prend pas toujours en charge tous les formats audio possibles, en fonction de ce qui est pris en charge par le système de base.

Vous voulez probablement faire ce qui suit:

  • Assurez-vous que l'ordinateur sur lequel vous exécutez le programme dispose d'une carte son raisonnable. La plupart du temps, lorsque je vois l'exception ci-dessus, je cours sur une machine serveur sans carte son intégrée ou avec une carte son vraiment boiteuse ou sans chemin audio.
  • Si vous utilisez un terminal distant ou quelque chose comme ça, assurez-vous que le son a une manière configurée de jouer.
  • Essayez de réencoder votre échantillon sonore à un débit différent, ou peut-être sous la forme d'un fichier WAV, puis essayez de le lire.
Questions connexes