java - 将带有音频的数组列表转换为 .wav 文件(Java)

标签 java audio arraylist wav

这是我的问题,有人给了我一个函数,如果我理解得很好,它将一些声音样本放入一个数组列表中。

我想用这个音轨创建一个 .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();
   }    
    }

最佳答案

在我看来,这不是一个好的 Java 源代码,因为有很多无用的操作可以使用一些特定的 Java 工具来自动化。

显然,您有一个庞大的类,它代表特定专辑的独特轨道;当然,这张专辑被分割为不同的样本。以下是方法的详细描述以及一些提示,以改进您的代码:

  • sortTrack() 方法用于根据 Sample 类中定义的特定排序标准对数据进行排序。在这种情况下,您应该使用特定的数据结构,该结构允许您维护所有自动排序的数据。我建议使用 TreeSet,但这种数据结构需要其中包含的元素必须实现 Comparable interface .
    这样,在每次插入操作中,您将始终根据您定义的标准对数据进行排序(根据您发布的代码,每个样本都使用其开始时间进行排序);
  • addSound() 方法将指定的 Sample 实例附加到您的示例列表中(如果您想切换到 TreeSet,该方法的实现不会改变);
  • deleteSound() 方法尝试从您的样本列表中删除一个样本,该样本应具有特定名称(fic 参数)和特定开始时间(sT 参数)。它是如何工作的?它循环直到找到具有指定样本名称和开始时间的对象,或者如果您到达列表的末尾(注意,for循环是空的,因为您需要做的就是继续并增加i,直到其中一个条件为假)。但是这种东西真的很糟糕,因为您应该改用提供 ArrayList 类(或者通常是 Collection interface 的子类的每个类)的 remove 方法。
    在这种情况下,您需要修复 Sample 类中的 equals() 方法,以便定义两个 Sample 何时相等。
  • 关于java - 将带有音频的数组列表转换为 .wav 文件(Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24282109/

    相关文章:

    java - modelmapper 跳过嵌套对象的属性

    java - 如何使用 Selenium Java Webdriver 切换 Bootstrap 开关?

    java - 在数组列表中存储值并打印它

    java - ArrayList.remove(int index) 不适用于非匿名类对象

    java - 对数组列表进行排序

    java - 什么是 NullPointerException,我该如何解决?

    java - 我正在向服务器发送 GET 方法,但接收 POST 方法

    python - Librosa Mel 谱图对数形状

    android - Android,我不知道如何停止这种声音循环

    iphone - 在快速按下 Xcode 按钮时快速播放声音的最佳方法是什么?