c++ - 如何在 C++ 中正确组织和实现 SFML 音频?

标签 c++ visual-studio-2012 audio sfml

对于我的一个高中独立学习项目,我必须使用 Visual C++ 中的 SFML 制作一个简单的游戏(特别是游戏“Snake”)(是的,我是 C++ 和 SFML 的新手)。我已经编写了游戏的核心和图形,现在我正在处理音频和音效。我已经在 SFML 书中阅读了一些关于音频的内容,但仍然对如何将其正确地实现到我的代码中感到困惑。我知道我必须制作一个 sf:Sound 和一个 sf::SoundBuffer 对象,分别使用 loadFromFile 和 openFromFile 加载声音和音乐,并分别使用 sound.play() 和 sound.stop() 播放和停止。然而,这就是问题所在。我是否在 main 方法中加载这些对象,我是否将它们作为全局对象以便我可以在整个代码中使用,我是否加载到发生 sfx 的函数中,我是否制作一个包含所有声音的对象?...通常,我如何在我的代码中正确组织和实现这些音频文件。这是我目前所拥有的:

主要方法

/*Main method*///
int main(){
    /*Initialize the objects*/
    Snake snake = Snake();
    sf::Text textCount;
    Apple apple(0, 0);
    apple.locateApple();
    sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight), "SFML Application" );
    /*Load the audio*/

    sf::Music backgroundMusic;
    sf::Sound eating;
    sf::SoundBuffer sb_eating;
    sf::Sound moving;
    sf::SoundBuffer sb_moving;
    sf::Sound losing;
    sf::SoundBuffer sb_losing;
    sf::Sound begin;
    sf::SoundBuffer sb_begin;

    if (!backgroundMusic.openFromFile("backgroundmusic.wav"))
        std::cerr << "Error opening \"backgroundmusic.wav\"" << std::endl;
    if (!sb_eating.loadFromFile("eatingsfx.wav"))
        std::cerr << "Error opening \"eatingsfx.wav\"" << std::endl;
    if (!sb_moving.loadFromFile("movingsfx.wav"))
        std::cerr << "Error opening \"movingsfx.wav\"" << std::endl;
    if (!sb_losing.loadFromFile("losingsfx.wav"))
        std::cerr << "Error opening \"losingsfx.wav\"" << std::endl;
    if (!sb_begin.loadFromFile("beginsfx.wav"))
        std::cerr << "Error opening \"beginsfx.wav\"" << std::endl;

    eating.setBuffer(sb_eating);
    moving.setBuffer(sb_moving);
    losing.setBuffer(sb_losing);
    begin.setBuffer(sb_begin);

    moving.setVolume(50);

    backgroundMusic.setLoop(true);
    backgroundMusic.play();

    /*Load the font*/
    sf::Font font;
    if (!(font.loadFromFile("arial.ttf")))
        std::cout << "Error loading fonts" << std::endl;
    /*Create the text*/
    textCount.setFont(font);
    textCount.setString(std::string("points: ") + std::to_string(points));
    textCount.setColor(sf::Color::Red);
    textCount.setCharacterSize(20);
    textCount.setPosition(windowWidth / 2 - (textCount.getString().getSize()*(textCount.getCharacterSize() / 5)), textCount.getCharacterSize() - 5);
    textCount.setStyle(sf::Text::Bold);

    window.draw(textCount);

    /*Set Framerate fps*/
    window.setFramerateLimit(15);

    /*MAIN GAME LOOP*/
    counterTick = 1;


    while (inGame)
    {
        std::string counter = std::to_string(counterTick);
        std::cout << "Tick: " + counter << std::endl;

        window.clear(sf::Color::Black);
        sf::Event event;
        while (window.pollEvent(event)){
            if (event.type == sf::Event::Closed)
                window.close();
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Key::Escape)) break;
        /*Call Updates*/
        snake.input();
        snake.checkReals();
        snake.moveUpdate();
        moving.play();

        /*Call Collisions*/
        std::cout << "     Outside Collision Loop " << std::endl;
        checkApple(snake, apple);
        checkBoundary(snake);

        /*Call Draw*/
        std::vector<sf::RectangleShape> shapearray = snake.draw();
        for (int i = shapearray.size() - 1; i >= 0; i--){
            window.draw(shapearray[i]);
        }
        window.draw(textCount);
        window.draw(apple.draw());
        window.display();

        counterTick++;

    }
    losing.play();
    backgroundMusic.stop();
    std::system("PAUSE");//bad practice, debuggin purposes
    return 0;
}

例如,当蛇与苹果相撞时,我如何才能播放“吃”音效?这是我的 checkApple() 方法:

检查 Apple 方法

void checkApple(Snake mA, Apple& mB){
    if ((mA.x[0] == mB.x()) && (mA.y[0] == mB.y())){
        dots += dotInterval;
        std::cout << "In Collision Method" << std::endl;
        points++;
        textCount.setString(std::string("points: ") + std::to_string(dots - 3));
        mB.locateApple();

    }
}

我也是这些论坛的新手,所以如果有任何问题请提问。

最佳答案

首先,我对 C++ 和 SFML 还很陌生。我确信有比我现有的更好的解决方案来解决您的问题,但这里有。

我有一个名为 loadAudio(std::string source) 的方法和一个用于存储音频的 vector 。

class Audio {

private:
    sf::SoundBuffer buffer;
    sf::Sound sound;
    std::string _src;
public:
    void init(std::string src) {        //Initialize audio
        _src = src;
        buffer.loadFromFile(src);
        sound.setBuffer(buffer);
    }
    void play(){
        sound.play();       // Play queued audio
    }
    void stop(){
        sound.stop();
    }
    //void setVolume(), void setPitch() ....


};

std::vector<Audio*> audio;

void loadAudio(std::vector<std::string> src) {
    audio.push_back(new Audio());
    audio.back()->init(src[i]);
}

所以基本上在游戏开始时我声明的声音是这样的:

loadAudio("sound/foo.wav");
loadAudio("sound/bar.wav");

然后我可以使用 audio[0]->play()

访问存储在 vector 中的声音

关于c++ - 如何在 C++ 中正确组织和实现 SFML 音频?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27235897/

相关文章:

python - 如何让 offsetof() 成为私有(private)类成员?

c++ - 如何在非网关接口(interface) linux 上检测互联网连接

sql-server - 如何在 Visual Studio 2012 中调试 SQL Server T-SQL

c# - 移至 .NET 4.5。获取 ""无法加载文件或程序集 _____ 或其依赖项之一。”错误

java - 录制时检测静音

系统为后台音频应用程序提供的 iOS 通知

javascript - HTML5 音频元素 - 搜索 slider - 无法在 'currentTime' 上设置 'HTMLMediaElement' 属性 : The provided double value is non-finite

c++ - 将 fpu 异常或 inf 投入工作是否可能/有效?

c++ - 带有 SDL2 的 Visual Studio 2012 中出现“函数中引用的未解析的外部符号 _SDL_main”错误

c++ - OpenGL:透视矩阵不显示任何内容