2014-01-19 32 views
1

我有以下代碼中,different sources混合,因爲我學習C++從C和PHP背景:金屬製品的聲音與罪()

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()返回一個「更好的質量」函數,還是我做了其他本質上錯誤的事情?在您有任何利益的情況下,這裏的開頭和其餘代碼:

#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 

回答

2

我覺得問題可能是:

unsigned long insin, insinb, factor; 

這些是整數類型。

嘗試改變這

float insin, insinb, factor; 
+0

事實上就是這樣。非常感謝。 –