SFML音频未播放

时间:2018-12-09 07:40:20

标签: c++ sfml

我有此代码:

#include <SFML/Audio.hpp>
#include <unistd.h>
#include <cmath>

int main()
{
    const double volume = 10000;
    const sf::Uint64 sampleCount = 44100;
    sf::Int16* samples = new sf::Int16[sampleCount];
    for (sf::Uint64 i = 0; i < sampleCount; i++) {
        samples[sampleCount] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
    }

    sf::SoundBuffer b;
    b.loadFromSamples(samples, sampleCount, 1, 44100);

    sf::Sound s;
    s.setBuffer(b);
    s.play();

    usleep(1000000);

    delete [] samples;

    return 0;
}

然后我编译:

g++ -o sound main.cpp -framework SFML -framework sfml-audio -F/Library/Frameworks

它应该以440 Hz的频率播放正弦波1秒钟,但它什么也没播放,只等一秒钟。

1 个答案:

答案 0 :(得分:0)

您的循环通过写入您不拥有的内存(特别是samples[sampleCount])来调用未定义的行为。我最好的猜测是它要么播放全零,要么播放随机静态,但由编译器确定精确度失败了。

此:

sf::Int16* samples = new sf::Int16[sampleCount];
for (sf::Uint64 i = 0; i < sampleCount; i++) {
    samples[sampleCount] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
}

需要成为

sf::Int16* samples = new sf::Int16[sampleCount];
for (sf::Uint64 i = 0; i < sampleCount; i++) {
    samples[i] = sin(((double)i / 44100.0)*M_PI*2.0*440) * volume;
}