【发布时间】:2014-06-10 01:43:36
【问题描述】:
有人可以帮我理解为什么下面的代码不起作用吗?
我通过调用方法start() 开始剪辑。此方法为要运行的剪辑创建一个新线程。但是,不,它似乎没有播放任何东西。
代码编译没有任何错误...
public class Audio
{
private Clip clip;
private Thread thread;
public Audio (String audioFile)
{
AudioInputStream audioStream = null;
URL audioURL = this.getClass().getClassLoader().getResource(audioFile);
// Obtain audio input stream from the audio file and load the information
// into main memory using the URL path retrieved from above.
try { audioStream = AudioSystem.getAudioInputStream(audioURL); }
catch (Exception e)
{
e.printStackTrace();
System.exit(1);
}
try
{
// Retrieve the object of class Clip from the Data Line.
this.clip = AudioSystem.getClip();
// Load the audio input stream into memory for future play-back.
this.clip.open(audioStream);
}
catch (LineUnavailableException e)
{
e.printStackTrace();
System.exit(1);
}
catch (IOException e)
{
e.printStackTrace();
System.exit(1);
}
}
public void start()
{
Runnable r = new Runnable() {
public void run()
{
loop();
}
};
thread = new Thread(r);
thread.start();
}
public void loop ()
{
// Rewind the media to the beginning of the clip.
this.clip.setFramePosition(0);
// Continuously play the clip.
this.clip.loop(Clip.LOOP_CONTINUOUSLY);
try
{
Thread.sleep(5000);
} catch (InterruptedException e)
{
e.printStackTrace();
}
}
更新
我发现了问题!问题是因为音频文件。我使用了不同的音频文件,我可以通过上面的代码听到声音。
编译的代码没有任何错误或警告真的很烦人。我通过获取音频格式检测到问题,然后将其传递给 DataLine.Info 类的对象。然后,从数据线中检索剪辑。
所以,基本上不是通过以下方式获取剪辑:
this.clip = AudioSystem.getClip();
我会通过以下方式获取剪辑:
AudioFormat format = audioStream.getFormat();
DataLine.Info info = new DataLine.Info(Clip.class, format);
this.clip = (Clip) AudioSystem.getLine(info);
当我用这个编译时,Java 抛出以下错误:
无线路匹配接口 Clip 支持格式 PCM_SIGNED 48000.0 Hz, 24 bit
所以,我替换了音频文件,它起作用了!
【问题讨论】:
-
API 显示继承的启动方法,你试过了吗(如this.clip.start)?
-
如果你在一个线程中全部尝试会发生什么?
-
回答您的问题: 1. 这不是Applet。我在另一个类中创建了这个类的一个对象。 2. 我试过clip.start(),但是没用。 3.在一个线程上启动剪辑也不起作用。我阅读了几篇关于此的文章,它们都建议在单独的线程上运行 clip.loop()。
-
我发现了问题。阅读我上面的新 cmets。