cocos2d-x 2.2.6 之 声音和音效(二)

在上一篇中,声音和音效的播放的主要接口,结果编写如下代码:

float m_MusicVol = 0.5f;  // (0.0f~1.0f)  音量大小
float m_WavVol = 0.5f;  // (0.0f~1.0f)  音效大小

CocosDenshion::SimpleAudioEngine::sharedEngine()->setBackgroundMusicVolume(m_MusicVol);
CocosDenshion::SimpleAudioEngine::sharedEngine()->setEffectsVolume(m_WavVol);

 

设置无效,查看了下,后来发现在代码中根本就没有对其相关处理,所以参考cocos2d-x中的TestCpp对其进行了修改,大概如下:

(1)打开MciPlayer.h文件,添加头文件:#include <Digitalv.h>,且添加接口,如下:

class MciPlayer
{
public:

  /*
    设置音量大小 0~1000
    */
    void SetVolume(UINT volume);

    /*
    获取音量大小 0~1000
    */
    UINT GetVolume() const;
};

(2)打开MciPlayer.cpp文件,以上接口实现代码如下:

void MciPlayer::SetVolume(UINT volume)
{
    if(!m_hDev)
        return;

    MCI_DGV_SETAUDIO_PARMS mciParams = {0};  
    mciParams.dwItem = MCI_DGV_SETAUDIO_VOLUME;  
    mciParams.dwValue = volume;  
    mciSendCommand(m_hDev, MCI_SETAUDIO, 
        MCI_DGV_SETAUDIO_ITEM | MCI_DGV_SETAUDIO_VALUE, (DWORD)&mciParams); 
}

UINT MciPlayer::GetVolume() const
{
    if(!m_hDev)
        return 0;

    MCI_STATUS_PARMS mciParams = {0};  
    mciParams.dwItem = MCI_DGV_STATUS_VOLUME;  
    mciSendCommand(m_hDev, MCI_STATUS, MCI_STATUS_ITEM, (DWORD)&mciParams); 

    return mciParams.dwReturn; 
}

 

(3)  打开SimpleAudioEngine.h,添加如下代码:

class EXPORT_DLL SimpleAudioEngine : public TypeInfo
{
private:
  float m_effectsVolume;    // 音效音量
};

 

(4)打开SimpleAudioEngine.cpp,添加如下代码:

SimpleAudioEngine::SimpleAudioEngine():
m_effectsVolume(1.0f)      // 音效音量初始化
{
}

unsigned int SimpleAudioEngine::playEffect(const char* pszFilePath, bool bLoop)
{
    unsigned int nRet = _Hash(pszFilePath);

    preloadEffect(pszFilePath);

    EffectList::iterator p = sharedList().find(nRet);
    if (p != sharedList().end())
    {
        p->second->Play((bLoop) ? -1 : 1);
        p->second->SetVolume((UINT) (m_effectsVolume * 1000.0f));   // 新代码添加
    }

    return nRet;
}

// volume interface
float SimpleAudioEngine::getBackgroundMusicVolume()
{
    //return 1.0; 
    return sharedMusic().GetVolume() / 1000.0f;
}

void SimpleAudioEngine::setBackgroundMusicVolume(float volume)
{
    sharedMusic().SetVolume((UINT)(volume * 1000.0f));
}

float SimpleAudioEngine::getEffectsVolume()
{
    //return 1.0;
    return m_effectsVolume;
}

void SimpleAudioEngine::setEffectsVolume(float volume)
{
    m_effectsVolume = volume;  
    EffectList::iterator iter;  
    for (iter = sharedList().begin(); iter != sharedList().end(); iter++)  
    {  
        iter->second->SetVolume((UINT) (volume * 1000.0f));  
    }
}

 

接下来编译代码,成功后,便可以控制音量大小了哦。

 

你可能感兴趣的:(cocos2d-x 2.2.6 之 声音和音效(二))