You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

SFML实现歌曲播放完毕后自动切换下一首的问题求解

问题原因

  • 你的sf::Music对象仅初始化加载了第一首《Fallen-Down.ogg》,当第一首播放结束进入Stopped状态时,直接调用play()只会重新播放当前已加载的音频文件,不会自动切换到第二首。
  • 缺少播放进度状态记录,没有在第一首播放结束后加载下一首音频的逻辑。
  • 直接用魔数0判断状态可读性差,建议直接使用SFML提供的枚举常量sf::Music::Stopped避免潜在问题。

修复后的完整代码

#include <iostream>
#include <vector>
#include <SFML/Window.hpp>
#include <SFML/Window/Event.hpp>
#include <SFML/Audio.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Graphics/RenderTarget.hpp>
#include <SFML/Audio/Music.hpp>

using namespace std;

int main (){
    sf::RenderWindow window(sf::VideoMode(800, 600), "My Window");
    // 定义播放列表
    const vector<string> playlist = {
        "Music/Fallen-Down.ogg",
        "Music/CORE.ogg"
    };
    int currentTrackIndex = 0;
    sf::Music music;

    // 加载并播放第一首
    if (!music.openFromFile(playlist[currentTrackIndex]))
        return EXIT_FAILURE;
    music.play();

    while (window.isOpen()){
        sf::Event event;
        while (window.pollEvent(event)) {
            if (event.type == sf::Event::Closed)
                window.close();                
        }
        
        // 检测当前音乐播放完毕
        if(music.getStatus() == sf::Music::Stopped) {
            currentTrackIndex++;
            // 判断还有下一首可播放
            if(currentTrackIndex < playlist.size()) {
                if(music.openFromFile(playlist[currentTrackIndex])) {
                    music.play();
                }
            }
            // 如需循环播放整个列表,可在这里添加逻辑:currentTrackIndex超出列表长度时重置为0即可
        }
    
        window.clear(sf::Color(255, 255, 255, 0));
        window.display();
    }
    return EXIT_SUCCESS;
}

内容的提问来源于stack exchange,提问作者Paul Giovanni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 13:57:00