-2

I wrote Snake code, and want to add a sound effect when snake eats an apple. I copyied a code from some guy on YT, but it doesn't work to me. Can somebody explain me how to do this?

Code:

import com.sun.tools.javac.Main;

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

public class AppleEatSoundEffect {
    public static Mixer mixer;
    public static Clip clip;

    public static void main(String[] args) {
        Mixer.Info[] mixInfos = AudioSystem.getMixerInfo();
        mixer = AudioSystem.getMixer(mixInfos[0]);

        DataLine.Info dataInfo = new DataLine.Info(Clip.class, null);
        try {
            clip = (Clip) mixer.getLine(dataInfo);
        } catch (LineUnavailableException lue) {
            lue.printStackTrace();
        }

        try {
            URL soundURL = Main.class.getResource("NotBad.wav");
            AudioInputStream audioStream = AudioSystem.getAudioInputStream(soundURL);
            clip.open(audioStream);
        } catch (LineUnavailableException lue) {
            lue.printStackTrace();
        } catch (UnsupportedAudioFileException uafe) {
            uafe.printStackTrace();
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }

            clip.start();
            do {
                try {
                    Thread.sleep(100);
                } catch (InterruptedException ie) {
                    ie.printStackTrace();
                }
            } while (clip.isActive());
        }
    }

Compiler says thas something wrong with clip = (Clip) mixer.getLine(dataInfo);:

Exception in thread "main" java.lang.IllegalArgumentException: Line unsupported: interface Clip at java.desktop/com.sun.media.sound.PortMixer.getLine(PortMixer.java:131)

Greedus
  • 1
  • 4
  • 3
    Why are you importing `com.sun.tools.javac.Main`? – shmosel Dec 24 '18 at 21:16
  • 2
    The [`javasound`](https://stackoverflow.com/tags/javasound/info) tag wiki has a correct example of setting up a `Clip`. That code from YouTube looks like garbage, honestly. I don't know what they think they're doing with `mixInfos[0]`. – Radiodef Dec 24 '18 at 21:27
  • You learn new things each day. (kidding) @shmosel This shouldn't be here at all. – MS90 Dec 24 '18 at 22:15
  • @shomel idk, Im really new to those things :) – Greedus Dec 24 '18 at 23:20
  • *"really new"* How did you go with the code linked by @Radiodef? – Andrew Thompson Dec 25 '18 at 06:03
  • `URL soundURL = Main.class.getResource("NotBad.wav");` I'd advise to print out the URL immediately afterwards. What value is returned? – Andrew Thompson Dec 25 '18 at 06:05
  • BTW @Radiodef, nice additions to the Java Sound WIKI. – Andrew Thompson Dec 25 '18 at 06:18
  • So, now a tried this code: `import javax.sound.sampled.AudioInputStream; import javax.sound.sampled.AudioSystem; import javax.sound.sampled.Clip; try { AudioInputStream audioIn = AudioSystem.getAudioInputStream(Main.class.getResource("beep-07.wav")); Clip clip = AudioSystem.getClip(null); clip.open(audioIn); clip.start(); }catch (Throwable t){} }` There are no errors, but no sound is played... – Greedus Dec 25 '18 at 16:56
  • 1) *"tried this code:"* Please [edit] it into the question where code is readable! 2) *"`catch (Throwable t){} }` There are no errors, but no sound is played..."* The `{}` in the `catch` means you have no information on what errors might have occurred. Change it to `{t.printStackTrace();}`. 3) Where is the code to print out the `soundURL`? 4) Tip: Add @shmosel (or whoever, the `@` is important) to *notify* the person of a new comment. – Andrew Thompson Dec 26 '18 at 07:22

1 Answers1

0

Below is a method which allows you to play audio files, in particular the common WAV or MIDI files. Try it...if you get your desired audio then let me know.

public Thread playWav(final File wavFile, final boolean... loopContinuous) {
    String ls = System.lineSeparator();
    // Was a file object supplied?
    if (wavFile == null) {
        throw new IllegalArgumentException(ls + "playWav() Method Error! "
                + "Sound file object can not be null!" + ls);
    }

    // Does the file exist?
    if (!wavFile.exists()) {
        throw new IllegalArgumentException(ls + "playWav() Method Error! "
                + "The sound file specified below can not be found!" + ls
                + "(" + wavFile.getAbsolutePath() + ")" + ls);
    }

    // Play the Wav file from its own Thread.
    Thread t = null;
    try {
        t = new Thread("Audio Thread") {
            @Override
            public void run() {
                try {
                    Clip clip = (Clip) AudioSystem.getLine(new Line.Info(Clip.class));
                    audioClip = clip;
                    clip.addLineListener((LineEvent event) -> {
                        if (event.getType() == LineEvent.Type.STOP) {
                            clip.drain();
                            clip.flush();
                            clip.close();
                        }
                    });
                    clip.open(AudioSystem.getAudioInputStream(wavFile));
                    // Are we to loop the audio?
                    if (loopContinuous.length > 0 && loopContinuous[0]) {
                        clip.loop(Clip.LOOP_CONTINUOUSLY);
                    }
                    clip.start();
                }
                catch (LineUnavailableException | UnsupportedAudioFileException | IOException ex) {
                    ex.printStackTrace();
                }
            }
        };
        t.start();
        Thread.sleep(100);
    }
    catch (InterruptedException e) {
        e.printStackTrace();
    }
    return t;
}

To use this method simply call it wherever and whenever you want a particular sound effect to be played:

File file = new File("resources/NotBad.wav");
playWav(file);

Make sure the file object points to the correct file location. If you want to loop the audio file as for perhaps game background music then supply boolean true to the optional loopContinuous parameter:

File file = new File("resources/BackgroundMusic.mid");
playWav(file, true);
DevilsHnd - 退職した
  • 8,739
  • 2
  • 19
  • 22