1

我不应该在循环样本长度的for循环中制作它吗?我不明白为什么它播放的是正弦波公式而不是锯齿波......这是从一个结构非常相似的哔哔声类修改而来的,也许是中间的 for 循环产生了太多的轮数而无法获得锯齿形状。你怎么看?这是我的代码:

class MakeSaw
{

  static void makeSaw(double f, int t) throws Exception
  {

    int nChannel = 1;         // number of channel : 1 or 2

    // samples per second
    float sampleRate = 16000;  // valid:8000,11025,16000,22050,44100
    int nBit = 16;             // 8 bit or 16 bit sample

    int bytesPerSample = nChannel*nBit/8;


    int bufferSize = (int) (nChannel*sampleRate*t*bytesPerSample);
    byte[] audioData = new byte[bufferSize];

    // "type cast" to ShortBuffer
    java.nio.ByteBuffer byteBuffer = java.nio.ByteBuffer.wrap(audioData);
    java.nio.ShortBuffer shortBuffer = byteBuffer.asShortBuffer();


    int sampleLength = audioData.length/bytesPerSample;

    // generate the wave
    double volume = 8192;   // 0-32767
    double PI = Math.PI;
    double sawWave=0;


        //make saw wave
        for(int i = 0; i < sampleLength; i++)
        {
            double time = i/sampleRate;
            sawWave = sawWave + Math.sin(2*PI*f*(i*t)/i);    //passing amplitude frequency and time
            short amplitude = (short) (volume*sawWave);

            for (int c=0;c<1;c++) //repeat once because audio playing on one channel
            {
                shortBuffer.put(amplitude);
            }
        }

    //end wave making//end generating sound wave sample


    boolean isSigned=true;
    boolean isBigEndian=true;

    // Define audio format
    javax.sound.sampled.AudioFormat audioFormat =
      new javax.sound.sampled.AudioFormat(sampleRate, nBit, nChannel, isSigned,isBigEndian);


    javax.sound.sampled.DataLine.Info dataLineInfo =
      new javax.sound.sampled.DataLine.Info(
         javax.sound.sampled.SourceDataLine.class, audioFormat);

    // get the SourceDataLine object
    javax.sound.sampled.SourceDataLine sourceDataLine = 
      (javax.sound.sampled.SourceDataLine)
      javax.sound.sampled.AudioSystem.getLine(dataLineInfo);

    sourceDataLine.open(audioFormat);
    sourceDataLine.start();

    // actually play the sound
    sourceDataLine.write(audioData,0,audioData.length);

    // "flush",  wait until the sound is completed
    sourceDataLine.drain();

  }


  public static void main(String[] args) throws Exception
  {

    makeSaw(400,2);
  }
}
4

1 回答 1

2

你的计算sawWave是错误的。所有的幅度都为零。

我没有尝试为你调试这个,但是有三件事很突出

        double time = i/sampleRate;
        sawWave = sawWave + Math.sin(2*PI*f*(i*t)/i);    //passing amplitude frequency and time
  1. 你没有timesawWave计算中使用。
  2. 这种划分i看起来很可疑。
  3. 为什么要sin()在生成锯齿波时使用?
于 2012-12-10T16:40:49.070 回答