SFML community forums

Help => Audio => Topic started by: analogue_bubblebath on March 21, 2021, 01:26:56 am

Title: Music starts playing when I close the window
Post by: analogue_bubblebath on March 21, 2021, 01:26:56 am
The file is supposed to play when I execute the game, but it only plays right when I close the window. The compiler throws no errors so I don't know what's wrong. The file works fine when I play it on my music player. I followed the official tutorial for this. Here's my "game" class, I created a Music object in the header, and this is the .cpp for it:

#include "Game.h"
#include <SFML/Graphics/RenderWindow.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Audio/Music.hpp>
#include <iostream>
using namespace std;
using namespace sf;

Game::Game() : m_w(VideoMode(720,480),"deadline"){
        m_w.setFramerateLimit(60);
        t2.loadFromFile("fondo.jfif");
        Fondo.setTexture(t2);
        Fondo.setPosition(0,-150);
        t3.loadFromFile("cara gato.png");
        CaraGato.setTexture(t3);
        CaraGato.setPosition(250,20);
        CaraGato.setScale(0.666,0.666);
        t4.loadFromFile("taza cafe.png");
        Taza.setTexture(t4);
        Taza.setPosition(500,20);
        Taza.setScale(0.666,0.666);
        t5.loadFromFile("sombrita 2.png");
        Sombra.setTexture(t5);
        Sombra.setPosition(-200,48);
        Sombra.setScale(2.0,2.0);
       
}


void Game::Run ( ) {
        while(m_w.isOpen()) {
                ProcesadoJuego();
                Update();
                Draw();
                stage_music.play();
        }
}



void Game::Draw ( ) {
        m_w.clear(Color(125,60,0,100));         ///maximo 255
        m_w.draw(Fondo);
        m_w.draw(CaraGato);
        m_w.draw(Taza);
        m_w.draw(Sombra);
        catt.Draw(m_w);
        m_w.display();
}

void Game::Update ( ) {
        catt.Update();
}

void Game::ProcesadoJuego ( ) {
        Event e;
        while(m_w.pollEvent(e)){ {
                if(e.type == Event::Closed)
                        m_w.close();   
                }
        }
        while(!stage_music.openFromFile("stage_music.ogg")) {
                cout << "ERROR" << endl;
        }
}


 

I know that this problem happens because I'm not placing the play() line correctly, I tried doing it in all of the functions from my "Game" class and none of that worked.

Do let me know if you need any more info on this issue.
Title: Re: Music starts playing when I close the window
Post by: G. on March 21, 2021, 04:52:14 am
When you call play on a sound or music that is already playing it restarts from the beginning, so if you're calling play every frame, your music restarts every frame, so you never have enough time hear it.

Don't call it your loop. Or don't call it if it's already playing, or call it only once when you want it to start.