Music Loop in Java

newbie picture newbie · Feb 2, 2011 · Viewed 22.9k times · Source

Good day!

I am doing a game and I want it to have a background sound. I created a class for it and I call it on my main. My code is as follows:

import sun.audio.*;
import java.io.*;

    public class Sound {

        public void music() {

            AudioStream backgroundMusic;
            AudioData musicData;
            AudioPlayer musicPlayer = AudioPlayer.player;
            ContinuousAudioDataStream loop = null;
            try {
                backgroundMusic = new AudioStream(new FileInputStream("chickendance.wav"));
                musicData = backgroundMusic.getData();
                loop = new ContinuousAudioDataStream(musicData);
                musicPlayer.start(loop);
            } catch (IOException error) { System.out.println(error);
            }
        }
    }

This is my main class where i call it.

public class HangmanLauncher extends javax.swing.JFrame {

        public HangmanLauncher() {
            initComponents();
            Sound sound = new Sound();
            sound.music();
        }

My problem is that the music doesn't play. Error: java.io.IOException: could not create audio stream from input stream. What does it mean? The type of my file is Microsoft Wave Sound Format and its size is 796kb. May I know what I am doing wrong? Your suggestions will be highly appreciated. Thank you in advance.

Answer

Eric Coffin picture Eric Coffin · Feb 2, 2011

I can play .wav files using the following code.

Mind you if you are using a JFrame you will likely want to play your sound file in a Thread so you can continue other operations.

import javax.sound.sampled.*;
import java.io.*;
import javax.swing.*;

AudioInputStream as1 = AudioSystem.getAudioInputStream(new java.io.FileInputStream("chickenDance.wav"));
               AudioFormat af = as1.getFormat();
               Clip clip1 = AudioSystem.getClip();
               DataLine.Info info = new DataLine.Info(Clip.class, af);

               Line line1 = AudioSystem.getLine(info);

               if ( ! line1.isOpen() )
               {
                clip1.open(as1);
                clip1.loop(Clip.LOOP_CONTINUOUSLY);
                clip1.start();
               }