我想要一个wav格式的声音文件(temp0x)在打开后编辑/删除。我正在使用线程播放声音,并在完成时关闭所有流。主线程然后应该删除它,但它没有这样做。如果我不先播放声音,删除它没有问题。打开后无法删除wav文件,java
这是playSound线程时播放的声音代码:
public void run() {
synchronized(this){
System.out.println("play sound: " + soundFile.getName());
AudioFormat format;
DataLine.Info info;
try {
stream = AudioSystem.getAudioInputStream(soundFile);
format = stream.getFormat();
info = new DataLine.Info(Clip.class, format);
clip = (Clip) AudioSystem.getLine(info);
clip.open(stream);
clip.start();
}catch(Exception ex){
ex.printStackTrace();
}
while(clip.getMicrosecondLength() != clip.getMicrosecondPosition()){
//waiting for sound to be finished
}
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
clip.addLineListener(new LineListener() {
public void update(LineEvent myLineEvent) {
if (myLineEvent.getType() == LineEvent.Type.STOP)
clip.close();
}
});
soundFile = null;
clip = null;
stream = null;
notify();
}
}
这是我的主线程代码:
PlaySound playSound = new PlaySound(filePath);
Thread play = new Thread(playSound);
play.start();
synchronized(play){
try{
System.out.println("Waiting for play to complete...");
play.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("play done");
}
if(new File("Sounds/Custom/temp0x.wav").delete()){
System.out.println("deleted");
} else
System.out.println("cannot delete");
}
它将打印无法删除。我一直盯着它几个小时,搜索我的袜子,但我找不到解决方案。有人可以帮我吗?
编辑::
如果我改变布尔删除检查的建议,这是我的输出(英文:没有存取权限,因为已经使用其它理线文件):
java.nio.file.FileSystemException: src\Opslaan.wav: Het proces heeft geen toegang tot het bestand omdat het door een ander proces wordt gebruikt.
at sun.nio.fs.WindowsException.translateToIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsException.rethrowAsIOException(Unknown Source)
at sun.nio.fs.WindowsFileSystemProvider.implDelete(Unknown Source)
at sun.nio.fs.AbstractFileSystemProvider.delete(Unknown Source)
at java.nio.file.Files.delete(Unknown Source)
at Main.main(Main.java:27)
编辑:: 问题似乎取决于平台。我需要Windows的解决方案。
您可能想尝试从您的调用中分离出您的文件创建('new File(“Sounds/Custom/temp0x.wav).delete())',然后确保该文件存在,并且路径是正确的,然后调用'delete'。 – Andy
首先,将'new File(“Sounds/Custom/temp0x.wav”)。delete()'改为'Files.delete(Paths.get(“Sounds/Custom/temp0x。 wav“))'。这样,你就会得到一个信息性的异常,它会给你更多关于为什么文件不能被删除的细节。第二,Object.wait()必须被调用请参阅[文档](http://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#wait--)以了解详细信息。 – VGR
在OS X中,我不知道根本没有遇到任何问题,按预期工作。 – mko