I hope the following program fully satisfies your request. If not, let me know what I need to fix and I'll update! This is as minimal as I can make it, all in the main.cpp-file:
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
#include <iostream>
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
bool wasKeyPressed = false; // Used so that it only detects the first keypress and not continuously.
sf::SoundBuffer m_origBuffer;
sf::SoundBuffer m_currBuffer;
sf::Sound m_sound;
void changeBuffer()
{
int sampleCount = m_origBuffer.getSampleCount();
const sf::Int16* origSamples = m_origBuffer.getSamples();
m_currBuffer.loadFromSamples(origSamples, sampleCount, m_origBuffer.getChannelCount(), m_origBuffer.getSampleRate());
sf::Time time = m_sound.getPlayingOffset();
std::cout << "Sound offset at change: " << time.asMilliseconds() << "\t";
m_sound.setBuffer(m_currBuffer);
m_sound.play();
m_sound.setPlayingOffset(time);
std::cout << "Offset set to time: " << time.asMilliseconds() << std::endl;
}
int main()
{
if (!m_origBuffer.loadFromFile("../Assets/Ape.wav"))
std::cout << "ERROR: Failed to load file!" << std::endl;
m_sound.setBuffer(m_origBuffer);
m_sound.setLoop(true);
m_sound.play();
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Num1))
{
if (!wasKeyPressed)
changeBuffer();
wasKeyPressed = true;
}
else
wasKeyPressed = false;
window.display();
}
return 0;
}
Pressing the 1 key makes the sound restart from the beginning of the clip. The debug printing of the time value shows that the first time, there is a value other than 0, but all the other times, the time is 0. This is peculiar as I would have expected some other value from getPlayingOffset().
I have tried two modifications to the code above:
- Commenting out the row m_sound.setBuffer(m_currBuffer); this worked, no lag and time != 0
- Changing that same row to m_sound.setBuffer(m_origBuffer); which also worked, no lag and time was != 0.
It is peculiar though, as this example merely copies the
m_origBuffer by sending the samples unchanged into the
m_currBuffer load function as well as copy all other information from
m_origBuffer. I can't make out what to do of it as I can't think of any ways of completing my assignment without changing buffers.
Thank you so much for the time you take to help me!