Extra2D/include/resource/audio.h

97 lines
1.9 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#pragma once
#include <resource/resource.h>
#include <SDL2/SDL_mixer.h>
#include <string>
namespace extra2d {
/**
* @brief 音频类型枚举
*/
enum class AudioType : uint8 {
Sound, // 音效(短音频,完全加载到内存)
Music // 音乐(流式播放)
};
/**
* @brief 音频资源类
*
* 封装 SDL2_mixer 音频
*/
class Audio : public Resource {
public:
Audio();
~Audio() override;
/**
* @brief 获取资源类型
*/
ResourceType getType() const override { return ResourceType::Audio; }
/**
* @brief 从文件加载音频
* @param path 文件路径
* @param type 音频类型
* @return 是否加载成功
*/
bool loadFromFile(const std::string& path, AudioType type);
/**
* @brief 播放音频
* @param loops 循环次数,-1 表示无限循环0 表示播放一次
*/
void play(int loops = 0);
/**
* @brief 暂停播放
*/
void pause();
/**
* @brief 恢复播放
*/
void resume();
/**
* @brief 停止播放
*/
void stop();
/**
* @brief 设置音量
* @param volume 音量0.0 - 1.0
*/
void setVolume(float volume);
/**
* @brief 获取音量
* @return 音量0.0 - 1.0
*/
float getVolume() const;
/**
* @brief 检查是否正在播放
*/
bool isPlaying() const;
/**
* @brief 检查是否已暂停
*/
bool isPaused() const;
/**
* @brief 获取音频类型
*/
AudioType getAudioType() const { return type_; }
private:
AudioType type_ = AudioType::Sound; // 音频类型
Mix_Chunk* chunk_ = nullptr; // 音效数据
Mix_Music* music_ = nullptr; // 音乐数据
int channel_ = -1; // 音效通道
float volume_ = 1.0f; // 音量
};
} // namespace extra2d