我想要一個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