Java Audio - How to play song during game (Application, not Applet)

允我心安 提交于 2019-12-11 06:38:42

问题


LAST EDIT - TWO SIMPLE ANSWERS NEEDED.

1) I was able to get the code working with a URL (it's the code from one of the responses below). But my song is in a wav file. When I try to do File url = new File("---");, it doesn't work.

Instead, in the stack trace (thanks for that tip!), it says

"Failed to allocate clip data: Requested buffer too large"

The song I'm trying to play is techno, about 3 minutes long.

How do I work around the clip data size issue?


回答1:


Look at the classes of the Java Sound API for sampled sound. Particularly the Clip interface and the AudioSystem class.

Java Sound uses the SPI to add support for extra formats to the defaults built in to the J2SE. You can add the JMF based mp3plugin.jar to provide support for MP3s to JavaSound.


For playing WAVs in a loop, see this small example..
import java.net.URL;
import javax.sound.sampled.*;

public class LoopSound {

  public static void main(String[] args) throws Exception {
    URL url = new URL(
      "http://pscode.org/media/leftright.wav");
    Clip clip = AudioSystem.getClip();
    AudioInputStream ais = AudioSystem.
      getAudioInputStream( url );
    clip.open(ais);
    clip.loop(5);
    javax.swing.JOptionPane.showMessageDialog(null, "Close to exit!");
  }
} 



回答2:


Check out this tutorial, it shows how to implement your own read-feed-play loop and avoid memory errors:

http://codeidol.com/java/swing/Audio/Play-Non-Trivial-Audio/



来源:https://stackoverflow.com/questions/3785652/java-audio-how-to-play-song-during-game-application-not-applet

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