首页 文章

SFML音频无法播放

提问于
浏览
0

我有这个代码:

#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赫兹的速度播放1秒的正弦波,但它不会播放任何东西,只需等待一秒钟 .

1 回答

  • 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;
    }
    

相关问题