首页 > 解决方案 > 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 秒钟,但它什么也不播放,只是等待一秒钟。

标签: c++sfml

解决方案


您的循环通过写入您不拥有的内存来调用未定义的行为,特别是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;
}

推荐阅读