2014-06-18 77 views
0

這是我的問題,有人給了我一個函數,如果我理解的很好,可以將一些聲音樣本放入數組列表中。將帶有音頻的ArrayList轉換爲.wav文件(Java)

我想用這個音軌創建一個.wav文件,我真的不知道該怎麼做。

下面是代碼,因爲也許我只是不明白它在所有...

public class Track { 



private ArrayList<Sample> sounds; 
private  AudioFormat audioFormat; 
      TargetDataLine targetDataLine; 
public Track() 
{ 
    this.sounds = new ArrayList <Sample>(); 
} 
/*** Sort the sample on the track by ascending start time ***/ 
public void sortTrack() { 
    Collections.sort(sounds); 
} 

/** 
* Add a sample to the track. 
* @param fic location to the audio file. 
* @param sT set the start time in ms of the sound on the track. 
*/ 
public void addSound(String fic, long sT) {  
    sounds.add(new Sample(fic, sT)); 
} 

/** 
* Delete a sample to the track. 
* @param fic location to the audio file. 
* @param sT set the start time in ms of the sound on the track. 
*/ 
public void deleteSound(String fic, long sT) {  
    int i; 
    for (i = 0; i < sounds.size() &&(
    sounds.get(i).getAudioFile().getName() == fic && 
    sounds.get(i).getStartTime() == sT); ++i) {} 
    if (i < sounds.size()) sounds.remove(i); 
} 

這是樣品,在上面的代碼進口。

public Sample (String fileLocation, long sT) { 

try{ 
    audioFile = new File(fileLocation); 
    istream = AudioSystem.getAudioInputStream(audioFile); 
    format = istream.getFormat(); 
    startTime = sT; 
    timeLenght = (audioFile.length()/(format.getFrameSize() * format.getFrameRate())) * 1000; 
} 
catch (UnsupportedAudioFileException e){ 
    e.printStackTrace(); 
     } catch (IOException e) { 
    e.printStackTrace(); 
    }  
    } 
+0

如何定義「Sample」?請包括進口。此外,#deleteSound(String,long)中有幾個明顯的問題, 。首先,String比較決不會使用==引用標識比較器,但總是使用#equals(Object)方法。這是因爲在Java中,字符串是對象,而不是原始值。另外,在手動迭代時刪除集合的元素收集是不好的做法Iterator及其#remove()操作。 – hiergiltdiestfu

回答

0

在我看來,這不是一個很好的Java源代碼,只是因爲有很多無用的操作,可以使用一些特定的Java工具來自動化。

顯然,你有一個巨大的類,它代表了一個特定專輯的獨特軌道;當然,這張專輯可以細分爲不同的樣本。如下的一些提示的方法的詳細描述,以改進代碼:

  • sortTrack()方法,以便用來根據在樣品類中定義的特定排序標準的數據進行排序。在這種情況下,您應該使用特定的數據結構,以授予您自動排序的所有數據。我建議TreeSet但這種數據結構需要包含在其中的元素必須實現Comparable interface。 通過這種方式,在每次插入操作時,您將始終根據您定義的標準對您的數據進行排序(從您發佈的代碼開始,每個樣本使用其開始時間進行排序);
  • addSound()方法將指定的Sample實例附加到樣本列表中(如果要切換到TreeSet,則方法的實現不會更改);
  • deleteSound()方法試圖從樣本列表中刪除應該有特定名稱(fic參數)和特定開始時間(sT參數)的樣本。它是如何工作的?它循環直到找到具有指定樣本名稱和開始時間的對象,或者如果您到達列表的末尾(請注意,for循環爲空,因爲您需要做的只是繼續並增加i,直到其中一個條件爲假)。但這種東西真的很糟糕,因爲您應該使用提供ArrayList類的方法(或者一般來說每個類都是Collection interface的子類。 )在這種情況下,您需要修復equals()方法,方法,以定義兩個Sample是否相等
相關問題