SFML 音频不播放
SFML Audio not playing
我有这个代码:
#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 秒,但它没有播放任何东西,只是等待一秒。
你的循环通过写入你不拥有的内存来调用未定义的行为,特别是 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;
}
我有这个代码:
#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 秒,但它没有播放任何东西,只是等待一秒。
你的循环通过写入你不拥有的内存来调用未定义的行为,特别是 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;
}