Java 中的音乐循环

发布于 2024-10-15 19:44:01 字数 1142 浏览 7 评论 0原文

再会!

我正在做一个游戏,我希望它有背景声音。我为它创建了一个类,并在我的 main 上调用它。我的代码如下:

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

这是我调用它的主类。

public class HangmanLauncher extends javax.swing.JFrame {

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

我的问题是音乐不播放。 错误:java.io.IOException:无法从输入流创建音频流。这是什么意思?我的文件类型是 Microsoft Wave Sound Format,大小为 796kb。我可以知道我做错了什么吗?我们将非常感谢您的建议。先感谢您。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

瑕疵 2024-10-22 19:44:01

我可以使用以下代码播放 .wav 文件。

请注意,如果您使用 JFrame,您可能希望在线程中播放声音文件,以便可以继续其他操作。

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

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();
               }
煮茶煮酒煮时光 2024-10-22 19:44:01

所以我一直在尝试自己做这件事,最后我找到了如何实现它
此特定代码从给定的目录中随机选择一个曲目,然后循环选择另一个随机文件
循环位于从 run() 方法调用的 startPlayback() 中,因为这是一个单独的线程,因此不会停止程序执行

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

}

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

}

零時差 2024-10-22 19:44:01

我的猜测是 wav 文件已以 AudioStream 类无法理解的格式进行编码。我找不到该类的文档 (??),但我会尝试另一个不是 Microsoft Wave Sound 的文件。同样,我不知道该编码的具体情况,但它可能是 Microsoft 专有的,因此不在 AudioStream 的 Sun 实现中。

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.

月寒剑心 2024-10-22 19:44:01

我相信这只是 mp3,但如果这是一个选项,请查看 JLayer 和朋友: http://www .javazoom.net/projects.html

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

小红帽 2024-10-22 19:44:01

我从这样的 Wave 中生成一个 AudioInputStream:

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

但我不播放它。

I produce an AudioInputStream from a Wave like this:

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

I don't play it though.

浅唱ヾ落雨殇 2024-10-22 19:44:01

我使用 .au 文件格式并且它有效。 :)

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

青丝拂面 2024-10-22 19:44:01

我尝试了许多不同的播放音频的方式,我发现这是我最成功的类文件。

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[]){
    }
}

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[]){
    }
}
皇甫轩 2024-10-22 19:44:01

感谢您的信息,在上述帮助和其他一些帮助下,我有了这个有效的代码:

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

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();
    }
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文