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 秒钟,但它什么也不播放,只是等待一秒钟。
解决方案
您的循环通过写入您不拥有的内存来调用未定义的行为,特别是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;
}
推荐阅读
- sql - 如何在一对多关系 SQL 中获取前 x 条记录
- reactjs - 在 React 中的管理员/用户视图之间切换
- android - Android Studio 打开一个片段但不改变底部导航菜单状态
- java - 尝试使用文件输入从数组创建对象时我做错了什么
- tensorflow - 递归地分配给 TensorFlow 中的变量切片
- cmd - 这是获取正在执行批处理文件的文件夹的合法“技巧”吗?
- python - 将 Spark DataFrame 中的 NULL 值替换为 Dict 的键值
- java - 哈希图中的字数
- javascript - IndexedDB 为简单对象占用大量空间
- graphql - 如何在 Hasura graphql 中查询另一个查询的结果?