如何更改此采样率转换代码以使声音变慢?

时间:2019-05-23 19:36:42

标签: java audio

对于此作业,我需要采用下面代码中显示的氦气类并进行传输,以使其变慢和变深,而不是变高和变快

我尝试更改一些int变量,但没有成功

public void helium(String sourceFile, String targetFile)
    {
        Sound sourceObj = new Sound(sourceFile);                                //Construct a new Sound object called sourceObj. A sourceObject now represents the sourceFile object.
        Sound target = new Sound(targetFile);                                   //Construct a new Sound object called target. The target object now represents the targetFile object.
        int sampleValue = 0;                                                    //The sampleValue variable is declare as an int and is initialized to 0.
        int targetIndex = 0;                                                    //The targetIndex variable is declared as an int and is initialized to 0.

        for(int index = 0; index < sourceObj.getLength(); index+=2)             //A for loop is created to traverse the length of the sourceObj. Notice that the loop increments by two each time, not 1.
        {
            sampleValue = sourceObj.getSampleValueAt(index);                    //The getSampleValueAt() method gets the sample value at index position of sampleObj.
            target.setSampleValueAt(targetIndex,sampleValue);                   //The setSampleValueAt() method sets the sample value at the targetIndex position in the target file.
            targetIndex++;                                                      //The targetIndex variable is incremented by 1 each time through the loop.
        }
        target.play();                                                          //The play() method is invoked on the target object to play the audio with the high pitched audio.
        target.write("heliumn.wav");                                            //The write() method is invoked on the target object and the audio with the new higher pitch is saved as a .wav file.
    }  

结果应使.wav听起来更慢和更深

2 个答案:

答案 0 :(得分:2)

从纯声学的角度考虑这一点。很简单,我相信您已经了解了它的工作原理。这是一个100Hz的正弦波。

100Hz sine wave

您可以通过简单地升高或降低声波的频率来改变其音高,对吗?因此,如果我们将该正弦波“压缩”到2倍,则会得到200Hz的正弦波,听起来音调更高。

200Hz sine wave

考虑到这一点,示例代码在做什么。对于原始声音中的每2个音频样本,我们将该样本写入新的目标声音。因此,我们完全丢弃其他所有样本。这使序列的长度成为1/2,从而增加了频率并提高了音高。

要延长/降低/降低声音的频率,您需要执行相反的操作,即,您需要在每个采样点复制数据。单步执行每个样本,而不是每两个样本,然后将该样本两次写入目标。

此过程称为sample rate conversion,其名称很清楚。采样率转换是您可以执行的最简单的音频拉伸形式。

答案 1 :(得分:0)

enter image description here
这是您想做什么与原来所做的事的直观构想