Archief - Java + sound

Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.

Sertu

Legacy Member
ik heb nog maar net begonnen met java te leren en ik ben momenteel terwijl ik een van die boeken van java voor beginners lees een simpel spelleke aant programmeren nl. zeeslag. Nu het spel werkt maar ik zou er nog graag een paar geluidjes bijhebben. Ik heb al gekeken op het net maar ik snap niet zo veel van wat ze daar uitleggen. Zou mss iemand het mij kunnen uitleggen of een klasse of methode schrijven waarmee ik het zou kunnen. Ik zal u zeer dankbaar zijn :bow: :bow:
Aj ja en tis nen app deje ik schrijf dus gene applet.

Kn0t

Legacy Member
Tot voor Java1.5 kon je met de klasse AudioClip perfect geluidjes afspelen:
Code:
AudioClip audioClip;
try
{
  audioClip = Applet.newAudioClip(new URL("sound.wav"));
}
catch(IOException e)
{
  e.printStackTrace();
}
audioClip.play(); // speel geluid 1x af
audioClip.loop(); // speel geluid af in een oneindige lus
audioClip.stop(); // stop
Ik heb dat altijd op die manier gedaan, maar vanaf ik Java1.5 geïnstalleerd heb, speelden (voornamelijk korte) soundclips vaak niet af. Ook met het meerdere keren simultaan afspelen van dezelfde audioclip zijn er problemen.
Na wat opzoeken op google en java fora heb ik een klasse geschreven die geluiden
wel correct afspeelt in Java1.5. http://www.knot.be/java/MyClip.java
Gebruik:
Code:
MyClip clip;
try
{
  clip = new MyClip(new URL("sound.wav"));
}
clip.play();
Probeer iig eerst gewoon met AudioClip. Wanneer dit problemen blijkt te geven kan je het altijd eens met MyClip proberen.

DiDoria

Legacy Member
Deze code werkt niet als ik wat aanpassingen doe (er zitten 2 fouten in bij mij)

C:\Documents and Settings\student\My Documents\ODM\MyClip.java:25: ';' expected
for (Mixer.Info mixerInfo : mixers)
^
C:\Documents and Settings\student\My Documents\ODM\MyClip.java:33: illegal start of expression
}
^
2 errors

Bewerking afgesloten het fout-code 1

Mss zien jullie de fout?
En mijn muziek, moet ik die met een mainklasse importeren ofzo?

QplQyer

Legacy Member
Toch met java 1.5 gecompileerd?
't is wel handiger om de fout te zien als de source erbij wordt gepaste :)

DiDoria

Legacy Member
Code:
import javax.sound.sampled.*;
import java.io.IOException;
import java.net.URL;

/**
 * This class provides a java 1.5 compatible AudioClip alternative.
 *
 * @author Jimmy Praet
 */
public class MyClip
{
    private final static Mixer mixer = getSoftwareMixer();
    private DataLine.Info dataLineInfo;
    private AudioInputStream audioInputStream;
    private Clip clip;

    /**
     * This method returns the software Mixer with the name 'Java Sound Audio Engine'
     *
     * @return the software Mixer if available, else null
     */
    private static Mixer getSoftwareMixer()
    {
        Mixer.Info[] mixers = AudioSystem.getMixerInfo();
        for (Mixer.Info mixerInfo : mixers)
        {
            if ("Java Sound Audio Engine".equals(mixerInfo.getName()))
            {
                return AudioSystem.getMixer(mixerInfo);
            }
        }
        return null;
    }

    /**
     * MyClip Constructor
     *
     * @param path URL referring to the location of the sound file
     */
    public MyClip(URL path)
    {
        try
        {
            audioInputStream = AudioSystem.getAudioInputStream(path);
            dataLineInfo = new DataLine.Info(Clip.class, audioInputStream
                    .getFormat(),
                    ((int) audioInputStream.getFrameLength() * audioInputStream
                    .getFormat().getFrameSize()));
            if (!AudioSystem.isLineSupported(dataLineInfo))
            {
                System.err.println("Audio-line not supported");
            }
        }
        catch (UnsupportedAudioFileException ex)
        {
            System.err.println("Audio-format not supported");
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        clip = createClip();
    }

    /**
     * Creates a new Clip instance of the same sound file
     *
     * @return Clip instance
     */
    private Clip createClip()
    {
        Clip clip = null;
        try
        {
            if (mixer != null)
            {
                clip = (Clip) mixer.getLine(dataLineInfo);
            }
            else
            {
                clip = (Clip) AudioSystem.getLine(dataLineInfo);
            }
            clip.open(audioInputStream);
        }
        catch (LineUnavailableException ex)
        {
            System.err.println("Audio line unavailable");
        }
        catch (IOException ex)
        {
            ex.printStackTrace();
        }
        return clip;
    }

    /**
     * Plays the audio clip. Even when the clip is already playing, this method will play the
     * clip simultaneously.
     */
    public void play()
    {
        if (!clip.isActive())
        {
            clip.setFramePosition(0);
            clip.start();
        }
        else
        // clip is already playing, create a new clip instance and play that one
        {
            Clip newClip = createClip();
            newClip.start();
        }
    }
}

C:\Documents and Settings\student\My Documents\ODM\MyClip.java:25: ';' expected
        for (Mixer.Info mixerInfo : mixers)
                                  ^
C:\Documents and Settings\student\My Documents\ODM\MyClip.java:33: illegal start of expression
    }
    ^
2 errors

Bewerking afgesloten het fout-code 1




De fout zal hem wel liggen in het feit dat ik geen mainklasse heb maar ik zou niet weten hoe ik hier mee moet beginnen eigelijk...

:sad:

DiDoria

Legacy Member
gevonden!!!
Code:
import java.io.*;
import javax.sound.sampled.*;

/**
    The SimpleSoundPlayer encapsulates a sound that can be opened
    from the file system and later played.
*/
public class SimpleSoundPlayer
{

    public static void main(String[] args) {
        // load a sound
        SimpleSoundPlayer sound =
            new SimpleSoundPlayer("sounds/music.midi");

        // create the stream to play
        InputStream stream =
            new ByteArrayInputStream(sound.getSamples());

        // play the sound
        sound.play(stream);

        // exit
        System.exit(0);
    }

    private AudioFormat format;
    private byte[] samples;

    /**
        Opens a sound from a file.
    */
    public SimpleSoundPlayer(String filename) {
        try {
            // open the audio input stream
            AudioInputStream stream =
                AudioSystem.getAudioInputStream(
                new File(filename));

            format = stream.getFormat();

            // get the audio samples
            samples = getSamples(stream);
        }
        catch (UnsupportedAudioFileException ex) {
            ex.printStackTrace();
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }
    }


    /**
        Gets the samples of this sound as a byte array.
    */
    public byte[] getSamples() {
        return samples;
    }


    /**
        Gets the samples from an AudioInputStream as an array
        of bytes.
    */
    private byte[] getSamples(AudioInputStream audioStream) {
        // get the number of bytes to read
        int length = (int)(audioStream.getFrameLength() *
            format.getFrameSize());

        // read the entire stream
        byte[] samples = new byte[length];
        DataInputStream is = new DataInputStream(audioStream);
        try {
            is.readFully(samples);
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }

        // return the samples
        return samples;
    }


    /**
        Plays a stream. This method blocks (doesn't return) until
        the sound is finished playing.
    */
    public void play(InputStream source) {

        // use a short, 100ms (1/10th sec) buffer for real-time
        // change to the sound stream
        int bufferSize = format.getFrameSize() *
            Math.round(format.getSampleRate() / 10);
        byte[] buffer = new byte[bufferSize];

        // create a line to play to
        SourceDataLine line;
        try {
            DataLine.Info info =
                new DataLine.Info(SourceDataLine.class, format);
            line = (SourceDataLine)AudioSystem.getLine(info);
            line.open(format, bufferSize);
        }
        catch (LineUnavailableException ex) {
            ex.printStackTrace();
            return;
        }

        // start the line
        line.start();

        // copy data to the line
        try {
            int numBytesRead = 0;
            while (numBytesRead != -1) {
                numBytesRead =
                    source.read(buffer, 0, buffer.length);
                if (numBytesRead != -1) {
                   line.write(buffer, 0, numBytesRead);
                }
            }
        }
        catch (IOException ex) {
            ex.printStackTrace();
        }

        // wait until all data is played, then close the line
        line.drain();
        line.close();

    }

}

Alleen kan hij geen mp3's aan moet ik dan bepaalde zaken importeren?
Het archief is een bevroren moment uit een vorige versie van dit forum, met andere regels en andere bazen. Deze posts weerspiegelen op geen enkele manier onze huidige ideeën, waarden of wereldbeelden en zijn op sommige plaatsen gecensureerd wegens ontoelaatbaar. Veel zijn in een andere tijdsgeest gemaakt, al dan niet ironisch - zoals in het ironische subforum Off-Topic - en zouden op dit moment niet meer gepost (mogen) worden. Toch bieden we dit archief nog graag aan als informatiedatabank en naslagwerk. Lees er hier meer over of start een gesprek met anderen.
Terug
Bovenaan