从使用C生成并使用aplay播放的正弦波中获得一半的频率和两倍的持续时间

hwazgwia  于 2023-06-21  发布在  其他
关注(0)|答案(2)|浏览(151)

我尝试使用以下C代码生成一个440Hz频率的正弦波,持续10秒:

#include <stdio.h>
#include <math.h>

double sine(double amp, double freq, double time);

int main(int argc, char *argv[])
{
    int sample_rate = 48000;
    double freq = 440;
    double amp = 1;
    double duration = 10;
    double time = 0;
    double val = 0;
    int temp = 0;
    int i = 0;

    FILE *fp = fopen("sine.bin", "wb");
    if (fp == NULL)
    {
        return -1;
    }
    while (i <= sample_rate * duration)
    {
        val = 32767.0 * sine(amp, freq, time);
        temp = (int) val;
        fwrite((const void*) &temp, sizeof(int), 1, fp);
        time = i / (1.0 * sample_rate);
        i++;
    }
}

double sine(double amp, double freq, double time)
{
    return amp * sin(2.0 * M_PI * freq * time);
}

然而,我得到的是一个220赫兹的正弦波,持续20秒钟。如何修改此代码以产生持续10秒的440Hz正弦波?我编译并运行了这段代码:

gcc sound.c  -Wall -Wextra -lm -o sound && ./sound
aplay -r 48000 -f S16_LE sine.bin
jdgnovmf

jdgnovmf1#

看起来很可疑。播放16位(小端序)流

aplay -r 48000 -f S16_LE sine.bin

然而写32位整数:

temp = (int) val;  // temp is declared as int
    fwrite((const void*) &temp,sizeof(short),1,fp);

我认为修复方法是用下面这行来替换上面的行:

short tmp2 = (short)val;  // or declare tmp2 as `int16_t` and include stdint.h
fwrite((const void*) &tmp2, sizeof(tmp2), 1, fp);
kq4fsx7k

kq4fsx7k2#

尝试生成16-bit声音文件时,使用int意味着它是32-bit64-bit,因此在处理16-bit音频时必须使用short
C Programming/limits.h

#include <stdio.h>
#include <math.h>

double sine(double amp, double freq, double time);

int main(int argc, char *argv[])
{
    int sample_rate = 48000;
    double freq = 220;
    double amp = 1;
    double duration = 10;
    double time = 0;
    double val = 0;
    short temp = 0;
    int i = 0;

    FILE *fp = fopen("sine.bin", "wb");
    if (fp == NULL)
    {
        return -1;
    }
    while (i <= sample_rate*duration)
    {
        val = 32767.0*sine(amp, freq, time);
        temp = (short) val;
        fwrite((const void*) &temp,sizeof(short),1,fp);
        time = i/(1.0*sample_rate);
        i++;
    }
}
double sine(double amp, double freq, double time)
{
        return amp*sin(2.0*M_PI*freq*time);
}

相关问题