2

I have SoundBuffer. I want this buffer move to Music. For now I save in file and read out, but I don't want saving. What can I do? Now I have this code:

sf::SoundBuffer sb = getSoundBuffer(new_channels,sample_rate);
sb.saveToFile("sound.wav");
std::unique_ptr<sf::Music> Buffer(new sf::Music());
Buffer->openFromFile("sound.wav")
 musicAlias[alias] = std::move(Buffer);
...
music->selected = musicAlias[alias].get();
Nejc Galof
  • 2,538
  • 3
  • 31
  • 70

1 Answers1

2

The class sf::Music is designed to be used for playing long audio data loaded from a file. If you want to play music that is in a sound buffer, then use sf::Sound like this:

sf::SoundBuffer sb = getSoundBuffer(new_channels,sample_rate);
std::unique_ptr<sf::Sound> Buffer(new sf::Sound( sb ));
musicAlias[alias] = std::move(Buffer);
...
music->selected = musicAlias[alias].get();

You may need to change the type of musicAlias to be a container of std::unique_ptr<sf::Sound>, but that should work, because the sf::Sound class provides a very similar interface as the sf::Music class.

Ralph Tandetzky
  • 22,780
  • 11
  • 73
  • 120
  • I have error like this: `error: cannot convert 'std::unique_ptr::pointer {aka sf::Sound*}' to 'sf::Music*' in assignment this->selected = musicAlias[alias].get();` – Nejc Galof Jan 16 '16 at 22:30
  • 1
    @neiiic Well, then change the type of the data member `selected` from `sf::Music*` to `sf::Sound*`. You may need to change types in some other places too. I don't know the rest of your program. – Ralph Tandetzky Jan 16 '16 at 22:34
  • Now I hear nothing. Without errors. If I replace back to Music, work. – Nejc Galof Jan 16 '16 at 22:45
  • `sf::SoundBuffer sb = getSoundBuffer(new_channels,sample_rate); sb.saveToFile("sound.wav"); std::unique_ptr Buffer(new sf::Sound(sb)); sf::Sound a; a.setBuffer(sb); a.play(); musicAlias[alias] = std::move(Buffer);` In wav file I can hear ok. But when I play sound in 2 different ways I can not hear anything. Why? – Nejc Galof Jan 16 '16 at 22:58
  • 2
    @neiiic Yeah. A local variable will be destroyed as soon as the function is left. For purposes of code maintainability, please don't make the variable `SoundBuffer` global, but make it a member variable of your class. – Ralph Tandetzky Jan 16 '16 at 23:21