Skip to content

Instantly share code, notes, and snippets.

@eXpl0it3r
Last active August 29, 2015 14:16
Show Gist options
  • Save eXpl0it3r/c4edb9bcc1f00e29a79b to your computer and use it in GitHub Desktop.
Save eXpl0it3r/c4edb9bcc1f00e29a79b to your computer and use it in GitHub Desktop.
Mixing Two SFML Sound Buffers
#include <SFML/Config.hpp>
#include <SFML/Audio.hpp>
#include <cmath>
#include <cstdint>
#include <vector>
int main()
{
sf::SoundBuffer buffer1, buffer2;
buffer1.loadFromFile("test1.wav");
buffer2.loadFromFile("test2.wav");
unsigned int channels = std::max(buffer1.getChannelCount(), buffer2.getChannelCount());
unsigned int rate = std::max(buffer1.getSampleRate(), buffer2.getSampleRate());
std::size_t size = std::max(buffer1.getSampleCount(), buffer2.getSampleCount());
std::vector<sf::Int16> samples(size, 0);
for(std::size_t i = 0; i < size; ++i)
{
sf::Int16 b1 = 0, b2 = 0;
if(i < buffer1.getSampleCount())
b1 = buffer1.getSamples()[i];
if(i < buffer2.getSampleCount())
b2 = buffer2.getSamples()[i];
// Mixing
if(b1 < 0 && b2 < 0)
samples[i] = (b1 + b2) - static_cast<sf::Int16>((b1 * b2) / INT16_MIN);
else if(b1 > 0 && b2 > 0)
samples[i] = (b1 + b2) - static_cast<sf::Int16>((b1 * b2) / INT16_MAX);
else
samples[i] = b1 + b2;
}
sf::SoundBuffer buffer;
buffer.loadFromSamples(samples.data(), samples.size(), ch, rate);
sf::Sound sound(buffer);
sound.play();
while(sound.getStatus() == sf::Sound::Playing)
{
// Wait
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment