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
相关产品推荐
相关产品推荐

