Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
715 views
in Technique[技术] by (71.8m points)

audio - Music Loop in Java

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...