Music Loop in Java

家住魔仙堡 提交于 2019-11-27 07:37:31

问题


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.


回答1:


My guess is that the wav file has been encoded in a format the AudioStream class doesn't understand. I couldn't find the docs for the class (??) but I would try another file that isn't Microsoft Wave Sound. Again, don't know the specifics of that encoding but it being Microsoft it's probably proprietary and therefore not in the Sun implementation of the AudioStream.




回答2:


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



回答3:


so i've been trying to do this myself and i found how to implement it finally This particular code chooses a track at random from the directory given and then loop choosing another random file The loop is in the startPlayback() which is called from the run() method, as this is a seperate thread this will not stop program execution

import java.io.*;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
/**
 *
 * @author Mangusbrother
 */

public class MusicPlayer extends Thread {private AudioStream as;
private AudioPlayer p;
private boolean playback;

public void run() {
    startPlayback();
}

private void setRandom() {
    File[] files = getTracks();
    try {
        String f = files[(int) (Math.random() * (files.length - 1))].getAbsolutePath();
        System.out.println("Now Playing: " + f);
        as = new AudioStream(new FileInputStream(f));
    } catch (IOException ex) {
        Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public void startPlayback() {
    playback = true;
    setRandom();
    p.player.start(as);
    try {
        do {
        } while (as.available() > 0 && playback);
        if (playback) {
            startPlayback();
        }
    } catch (IOException ex) {
        Logger.getLogger(MusicPlayer.class.getName()).log(Level.SEVERE, null, ex);
    }

}

public void stopPlayback() {
    playback = false;
    p.player.stop(as);
}

private File[] getTracks() {
    File dir = new File(System.getProperty("user.dir") + "\\music");
    File[] a = dir.listFiles();
    ArrayList<File> list = new ArrayList<File>();
    for (File f : a) {
        if (f.getName().substring(f.getName().length() - 3, f.getName().length()).equals("wav")) {
            list.add(f);
        }
    }
    File[] ret = new File[list.size()];
    for (int i = 0; i < list.size(); i++) {
        ret[i] = list.get(i);
    }
    return ret;
}

}




回答4:


I believe this is mp3-only, but if that's an option, check out JLayer and friends: http://www.javazoom.net/projects.html




回答5:


I produce an AudioInputStream from a Wave like this:

AudioSystem.getAudioInputStream(new FileInputStream("chickendance.wav"));

I don't play it though.




回答6:


I Used .au file format and it worked. :)




回答7:


I have tried many different ways of playing audio, and I have found this to be my most successful class file that does so.

package Classes;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import sun.audio.AudioData;
import sun.audio.AudioPlayer;
import sun.audio.AudioStream;
import sun.audio.ContinuousAudioDataStream;
public class SoundLoader2 implements Runnable{
    public AudioPlayer Player = AudioPlayer.player;
    public AudioStream Stream = null;
    public AudioData data=null;
    InputStream inputStream=null;
    InputStream inputStream2=null;
    InputStream Stream2=null;
    public ContinuousAudioDataStream loop;
    public String url;
    public URL Url;
    public boolean repeat;
    public SoundLoader2(String url,boolean repeat)throws IOException{
    this.repeat=repeat;
    Url=getClass().getResource(url);
     inputStream = Url.openStream();
     inputStream2 = Url.openStream();
        Stream=new AudioStream(inputStream);
        data=Stream.getData();
        loop = new ContinuousAudioDataStream(data);
        Stream2=new AudioStream(inputStream2);
    }
    public void play(){
    if(this.repeat==true){
        Player.start(loop);
        }
        else if(this.repeat==false);
        Player.start(Stream2);
        }
    @Override
    public void run() {
      play();
    }
    public static void main(String args[]){
    }
}



回答8:


thanks for the info, with above help and some others i have this code which works:

public void play(InputStream inputStream) {
    try {
        AudioInputStream soundIn = AudioSystem.getAudioInputStream(new BufferedInputStream(inputStream) );
        AudioFormat format = soundIn.getFormat();
        DataLine.Info info = new DataLine.Info(Clip.class, format);

        Clip clip = (Clip) AudioSystem.getLine(info);
        clip.open(soundIn);
        clip.start();
        sleep(clip.getMicrosecondLength() / 1000);// Thread.yield();
    } catch (Exception e) {
        log.warn("could not play");
        e.printStackTrace();
    }
}

private void sleep(long sleep) {
    try {
        Thread.sleep(sleep);
    } catch (InterruptedException ex) {
        Thread.currentThread().interrupt();
    }
}


来源:https://stackoverflow.com/questions/4875080/music-loop-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!