来自sin()的声音产生的金属声音

时间:2014-01-19 16:45:21

标签: c++ linux audio sin

我有以下代码,different sources的混合,因为我正在从C和PHP背景学习C ++:

int main() {
  const unsigned int sampleRate = 48000;
  // prepare a 6 seconds buffer and write it
  const unsigned long int size = sampleRate*6;
  float sample[size];
  unsigned long int i = 0;
  unsigned long insin, insinb, factor;

  // Multiply for 2*pi and divide by sampleRate to make the default period of 1s
  // So the freq can be stated in Hz
  factor = 2*3.141592;

  for (i; i<size; i++) {
    // Store the value of the sin wave
    insin = 440*float(i)*factor/float(sampleRate);
    insinb = 880*float(i)*factor/float(sampleRate);

    if (i > size/8)
      // Attempt to make it sound more instrument-like
      sample[i] = 0.7 * sin(insin) + 0.3 * sin(insinb);
    else
      sample[i] = 0.7 * sin(insinb) + 0.3 * sin(insin);

    // DEBUG
    if (i < 1000)
      printf("%f\n", sample[i]);
    }

  writeWAVData("sin.mp3", sample, size, sampleRate, 1);
  return 1;
  }

它会创建.mp3文件。然而,它总是1秒长,它有一个非常金属般的声音。从// DEBUG,我检索的值不是真正的正弦值。一小部分:

0.637161
0.637161
0.637161
0.070853
0.070853
0.070853
0.070853
0.070853
0.070853
0.070853
0.070853
0.070853
-0.383386
-0.383386
-0.383386
-0.383386
-0.383386

我认为金属声音可能来自sin()返回值过于方形的事实。为什么会这样? 我可以让sin()返回“质量更好”的功能,还是我在做其他本来就错误的事情?如果您有任何兴趣,这里是代码的开头和其余部分:

#include <fstream>
#include <cmath>
#include <sndfile.hh>

template <typename T>
void write(std::ofstream& stream, const T& t) {
  stream.write((const char*)&t, sizeof(T));
  }

template <typename SampleType>
void writeWAVData(const char* outFile, SampleType* buf, size_t bufSize,
                  int sampleRate, short channels)
  {
  std::ofstream stream(outFile, std::ios::binary);
  stream.write("RIFF", 4);
  write<int>(stream, 36 + bufSize);
  stream.write("WAVE", 4);
  stream.write("fmt ", 4);
  write<int>(stream, 16);
  write<short>(stream, 1);                                        // Format (1 = PCM)
  write<short>(stream, channels);                                 // Channels
  write<int>(stream, sampleRate);                                 // Sample Rate
  write<int>(stream, sampleRate * channels * sizeof(SampleType)); // Byterate
  write<short>(stream, channels * sizeof(SampleType));            // Frame size
  write<short>(stream, 8 * sizeof(SampleType));                   // Bits per sample
  stream.write("data", 4);
  stream.write((const char*)&bufSize, 4);
  stream.write((const char*)buf, bufSize);
  }

我只是通过在Linux(Ubuntu 13.10)中执行此操作来编译它:

 g++ audio.cpp -o audio && ./audio

1 个答案:

答案 0 :(得分:2)

我认为问题可能是:

unsigned long insin, insinb, factor;

这些是整数类型。

尝试将此更改为

float insin, insinb, factor;