main.cpp
#include <iostream>
#include <SoundPlayer.hpp>
const int sampleRate = 8000;
const int sampleRate2 = sampleRate / 2;
int main()
{
sf::Int16 b[sampleRate2];
SoundPlayer s(sampleRate);
s.Start();
double amplitude = 0.5 * 0xFFFF;
double frequency = 200;
char res = 0;
while (s.GetStatus() == s.Playing)
{
sf::Sleep(0.15f);
std::cout << "Press enter to add more samples." << std::endl;
std::cin.get(res);
if (res != '\n')
break;
for (int i = 0; i < sampleRate2; i++)
b[i] = (short)(amplitude * sin((2 * 3.14159 * i * frequency) / sampleRate));
frequency += 25;
s.Add(b, sampleRate2);
}
s.End();
return 0;
}
SoundPlayer.hpp
#pragma once
#include <iterator>
#include <SFML/Audio.hpp>
class SoundPlayer : public sf::SoundStream
{
sf::Mutex mutex; // for buffer
std::vector<sf::Int16> buffer;
std::vector<sf::Int16> playingBuffer;
size_t offset;
bool playing;
virtual bool OnGetData(sf::SoundStream::Chunk& data);
virtual void OnSeek(float timeOffset);
public:
SoundPlayer(int sampleRate);
~SoundPlayer();
void Start();
void End();
void Add(sf::Int16* data, size_t count);
};
SoundPlayer.cpp
#include <SoundPlayer.hpp>
SoundPlayer::SoundPlayer(int sampleRate)
: playing(false)
{
Initialize(1, sampleRate);
SetLoop(false);
}
SoundPlayer::~SoundPlayer()
{
End();
}
void SoundPlayer::Start()
{
if (playing)
return;
playing = true;
Play();
}
void SoundPlayer::End()
{
if (!playing)
return;
playing = false;
Stop();
}
void SoundPlayer::Add(sf::Int16* data, size_t count)
{
sf::Lock lock(mutex);
std::copy(data, data + count, std::back_inserter(buffer));
}
bool SoundPlayer::OnGetData(sf::SoundStream::Chunk& data)
{
if (!playing)
return false;
while (!buffer.size() && playing)
sf::Sleep(0.01f);
{
sf::Lock lock(mutex);
playingBuffer.assign(buffer.begin(), buffer.end());
buffer.clear();
}
if (!playingBuffer.size())
return false;
data.Samples = &playingBuffer[0];
data.NbSamples = playingBuffer.size();
return true;
}
void SoundPlayer::OnSeek(float timeOffset)
{
}