//////////////////////////////////////////////////////////////////////////////////////////////////////
// Crative Commons License: http://creativecommons.org/licenses/by/2.0/
// Do whatever you like with the code, but I want credit (if you copy&paste, include these lines)
// Or you could always modify it until I dont recognise it, thats cool with me :)
// - Denis Lukianov
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include <string>
//////////////////////////////////////////////////////////////////////////////////////////////////////
#include "iTunesCOMInterface.h" // Get this from the iTunes SDK
// Remember to add "iTunesCOMInterface_i.c" to your project to avoid linker errors
//////////////////////////////////////////////////////////////////////////////////////////////////////
std::string GetCurrentSongTitle_iTunes()
{
using std::string;
using std::wstring;
IiTunes *iITunes = 0;
IITTrack *iITrack = 0;
// String operations done in a wstring, then converted for return
wstring wstrRet;
string strRet;
CoInitialize(0);
try
{
HRESULT hRes;
BSTR bstrURL = 0;
// Create itunes interface
hRes = ::CoCreateInstance(CLSID_iTunesApp, NULL, CLSCTX_LOCAL_SERVER, IID_IiTunes, (PVOID *)&iITunes);
if(hRes == S_OK && iITunes)
{
ITPlayerState iIPlayerState;
iITunes->get_CurrentTrack(&iITrack);
iITunes->get_CurrentStreamURL((BSTR *)&bstrURL);
if(iITrack)
{
BSTR bstrTrack = 0;
iITrack->get_Name((BSTR *)&bstrTrack);
// Add song title
if(bstrTrack)
wstrRet += bstrTrack;
iITrack->Release();
}
else
{
// Couldn't get track name
}
// Add url, if present
if(bstrURL)
{
wstrRet += L" ";
wstrRet += bstrURL;
}
iITunes->get_PlayerState(&iIPlayerState);
// Add player state, if special
switch(iIPlayerState)
{
case ITPlayerStatePlaying:
default:
break;
case ITPlayerStateStopped:
wstrRet += L" [stopped]";
break;
case ITPlayerStateFastForward:
wstrRet += L" [fast]";
break;
case ITPlayerStateRewind:
wstrRet += L" [rewind]";
break;
}
iITunes->Release();
}
else
{
// iTunes interface not found/failed
wstrRet = L"";
}
}
catch(...)
{
try
{
if(iITunes)
iITunes->Release();
if(iITrack)
iITrack->Release();
}
catch(...)
{
}
}
CoUninitialize();
// Convert the result from wstring to string
size_t len = wstrRet.size();
strRet.resize(len);
for(size_t i = 0; i < len; i++)
strRet[i] = static_cast<char>(wstrRet[i]);
return strRet;
}
//////////////////////////////////////////////////////////////////////////////////////////////////////