我试图模仿这里找到的代码https://stackoverflow.com/tags/javasound/info,但我不能通过loop()或start()来播放它。我已经找到了答案,但似乎我只是一个侥幸或者是一个愚蠢的错误,其他人都很好地认出来。
import javax.sound.sampled.*;
import java.net.URL;
public class AudioTest
{
public static void main(String[] args) throws Exception
{
URL url = new URL("http://www.public.asu.edu/~wnjones1/leftright.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream audioIn = AudioSystem.getAudioInputStream(url);
clip.open(audioIn);
clip.start();
}
}
它拥有示例缺少GUI的所有内容,但这应该无关紧要,不是吗?它应该仍然能够至少播放一次吗?
非常感谢任何帮助。谢谢!
- EDIT-- 这是一个简单的两秒.wav文件,我从我的网站上拉。我使用的是Java7u21。
- 编辑v2.0-- 基本上我学到的是......保持GUI。或者使用Applet,这样您就不必担心main()结尾了。
import javax.swing.*;
public class Assignment6me extends JApplet
{
private int APPLET_WIDTH = 400, APPLET_HEIGHT = 160;
private AudioPanel ap;
//The method init initializes the Applet with a Pane with two tabs
public void init()
{
try
{
ap = new AudioPanel();
}
catch(Exception e)
{}
getContentPane().add(ap);
setSize (APPLET_WIDTH, APPLET_HEIGHT); //set Applet size
}
}
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
import java.io.File;
public class AudioPanel extends JPanel
{
public AudioPanel() throws Exception
{
File file = new File("Don't Stop Believin'.wav");
Clip clip = AudioSystem.getClip();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.getAudioInputStream( file );
clip.open(ais);
clip.start();
}
}
答案 0 :(得分:1)
在Java声音信息上看到的(工作)源代码。页面正好。
import java.net.URL;
import javax.swing.*;
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();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
SwingUtilities.invokeLater(new Runnable() {
public void run() {
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
}
});
}
}
我提请你注意:
// A GUI element to prevent the Clip's daemon Thread
// from terminating at the end of the main()
JOptionPane.showMessageDialog(null, "Close to exit!");
添加该部分,它应该没问题。
所以没有GUI就无法播放任何文件?
我无法回想起基于命令行的应用。这确实发挥了作用,但它是可能的。
import java.net.URL;
import javax.swing.*;
import javax.sound.sampled.*;
import java.util.Scanner;
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();
// getAudioInputStream() also accepts a File or InputStream
AudioInputStream ais = AudioSystem.
getAudioInputStream( url );
clip.open(ais);
clip.loop(Clip.LOOP_CONTINUOUSLY);
Scanner scanner = new Scanner (System.in);
scanner.nextInt();
}
}