I got the code from
https://www.sfml-dev.org/tutorials/2.5/audio-streams.php and replaced
const int samplesToStream = 50000;
to
const int samplesToStream = getSampleRate()/factor;
It worked fine until factor was 4 (or 4^k: 4,16,64...). In case if factor == 4^k, sound doesn't play and the app closes immediately with no errors
#include <SFML/Audio.hpp>
#include <vector>
// custom audio stream that plays a loaded buffer
class MyStream : public sf::SoundStream
{
public:
void load(const sf::SoundBuffer& buffer)
{
// extract the audio samples from the sound buffer to our own container
m_samples.assign(buffer.getSamples(), buffer.getSamples() + buffer.getSampleCount());
// reset the current playing position
m_currentSample = 0;
// initialize the base class
initialize(buffer.getChannelCount(), buffer.getSampleRate());
}
private:
virtual bool onGetData(Chunk& data)
{
// number of samples to stream every time the function is called;
// in a more robust implementation, it should be a fixed
// amount of time rather than an arbitrary number of samples
const std::size_t samplesToStream = getSampleRate()/4;
// set the pointer to the next audio samples to be played
data.samples = &m_samples[m_currentSample];
// have we reached the end of the sound?
if (m_currentSample + samplesToStream <= m_samples.size())
{
// end not reached: stream the samples and continue
data.sampleCount = samplesToStream;
m_currentSample += samplesToStream;
return true;
}
else
{
// end of stream reached: stream the remaining samples and stop playback
data.sampleCount = m_samples.size() - m_currentSample;
m_currentSample = m_samples.size();
return false;
}
}
virtual void onSeek(sf::Time timeOffset)
{
// compute the corresponding sample index according to the sample rate and channel count
m_currentSample = static_cast<std::size_t>(timeOffset.asSeconds() * getSampleRate() * getChannelCount());
}
std::vector<sf::Int16> m_samples;
std::size_t m_currentSample;
};
int main()
{
// load an audio buffer from a sound file
sf::SoundBuffer buffer;
buffer.loadFromFile("sound.ogg");
// initialize and play our custom stream
MyStream stream;
stream.load(buffer);
stream.play();
// let it play until it is finished
while (stream.getStatus() == MyStream::Playing)
sf::sleep(sf::seconds(0.1f));
return 0;
}
OS: Ubuntu 20.04.3 LTS
SFML version: 2.5.1