Exemplo n.º 1
0
//-----------------------------------------------------------------------------
//	Создание Direct Sound объекта
// на входе    :  window		 - идентификатор окна
//  			  clsid_direct   - идентификатор Direct Sound
//  			  device		 - идентификатор устройства воспроизведения
//  			  level 		 - уровень кооперации
// на выходе   :	указатель на созданный Direct Sound объект, если значение
//  			  равно 0 значит создание не состоялось
//-----------------------------------------------------------------------------
LPDIRECTSOUND ds_Create(HWND window, REFCLSID clsid_direct, LPGUID device,
	int level)
{
	// установка переменных
	LPDIRECTSOUND direct = 0;

	// Инициализация COM
	CoInitialize(NULL);

	// Создание Direct Sound обьекта
	if (CoCreateInstance(clsid_direct,
			NULL,
			CLSCTX_INPROC_SERVER,
			IID_IDirectSound,
			(void * *) &direct) != DS_OK)
		return false;

	// инициализация устройства воспроизведения
	if (direct->Initialize(device) != DS_OK)
		return false;

	// установка приоритетного режима
	if (direct->SetCooperativeLevel(window, level) != DS_OK)
		return false;

	return direct;
}
Exemplo n.º 2
0
// ==============================  INITIALIZE FORM =======================================
void TsounEditForm::DoFormInitialize()
{
	TTagEditForm::DoFormInitialize();

#if OPT_WINOS
	if( lpDirectSound )
		lpDirectSound->SetCooperativeLevel( GetWindow()->GetHWND(), DSSCL_NORMAL );
#endif
}
Exemplo n.º 3
0
int audioStreamer_ds::Open(int iswrite, int srate, int nch, int bps, int sleep, int nbufs, int bufsize, GUID *device)
{
  // todo: use device
  m_sleep = sleep >= 0 ? sleep : 0;

  GUID zero={0,};
  if (!memcmp(device,&zero,sizeof(zero))) device=NULL;

  m_nch = nch;
  m_srate=srate;
  m_bps=bps;

  int fmt_align=(bps>>3)*nch;
  int fmt_mul=fmt_align*srate;
  WAVEFORMATEX wfx={
		WAVE_FORMAT_PCM,
		nch,
		srate,
		fmt_mul,
		fmt_align,
		bps,
		0
	};
  m_totalbufsize=nbufs*bufsize;

  if (iswrite)
  {
      DirectSoundCreate(device,&m_lpds,NULL);

      if (m_lpds)
      {
        HWND hWnd = GetForegroundWindow();
        if (hWnd == NULL) hWnd = GetDesktopWindow();
        m_lpds->SetCooperativeLevel(hWnd,DSSCL_PRIORITY);

        // create a secondary buffer for now
        DSBUFFERDESC ds={sizeof(ds),DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_GLOBALFOCUS,m_totalbufsize,0,&wfx, };
        m_lpds->CreateSoundBuffer(&ds,&m_outbuf,NULL);
        
      }

  }
  else
  {
    DirectSoundCaptureCreate(device,&m_lpcap,NULL);
    if (m_lpcap)
    {
      DSCBUFFERDESC ds={sizeof(ds),0,m_totalbufsize,0,&wfx, };
      m_lpcap->CreateCaptureBuffer(&ds,&m_inbuf,NULL);
    }
  }

  m_bufsize=bufsize;


  return 0;
}
Exemplo n.º 4
0
static BRESULT dsoundcreate(HWND hWnd)
{
	// DirectSoundの初期化
	if (FAILED(DirectSoundCreate(0, &pDSound, 0))) {
		goto dscre_err;
	}
	if (FAILED(pDSound->SetCooperativeLevel(hWnd, DSSCL_PRIORITY)))
	{
		if (FAILED(pDSound->SetCooperativeLevel(hWnd, DSSCL_NORMAL)))
		{
			goto dscre_err;
		}
	}
	return(SUCCESS);

dscre_err:
	RELEASE(pDSound);
	return(FAILURE);
}
Exemplo n.º 5
0
void SNDDMA_Activate() {
	if ( !pDS ) {
		return;
	}

	if ( DS_OK != pDS->SetCooperativeLevel( GMainWindow, DSSCL_PRIORITY ) ) {
		common->Printf( "sound SetCooperativeLevel failed\n" );
		SNDDMA_Shutdown();
	}
}
Exemplo n.º 6
0
/*
=================
SNDDMA_Activate

When we change windows we need to do this
=================
*/
void SNDDMA_Activate( void ) {
	if ( !pDS ) {
		return;
	}

	if ( DS_OK != pDS->SetCooperativeLevel( g_wv.hWnd, DSSCL_PRIORITY ) )	{
		Com_Printf ("sound SetCooperativeLevel failed\n");
		SNDDMA_Shutdown ();
	}
}
Exemplo n.º 7
0
// initialize
bool sspDSDeviceGroup::initializeImpl(LPVOID hWnd)
{
	if (m_pDS.size() > 0) return TRUE;	// Already initialized

    if (hWnd == NULL)
    {
        // Error, invalid hwnd
        DOUT (_T("ERROR: Invalid parameters, unable to initialize services\n\r"));
        return FALSE;
    }
	m_hApp = (HWND) hWnd;
    setBufferFormat(2);
	m_pDS.reserve(m_nDevices.size());
	m_pDSBuf.reserve(m_nDevices.size());
	for (unsigned int i=0; i<m_nDevices.size(); i++) {
		// Create DirectSound object
		LPDIRECTSOUND ds;
		HRESULT nResult = DirectSoundCreate(m_dsInfo[m_nDevices[i]]->lpGuid, &ds, NULL);
		if (nResult == DS_OK) {
			nResult = ds->SetCooperativeLevel(m_hApp, DSSCL_PRIORITY);
			if (nResult == DS_OK) {
				LPDIRECTSOUNDBUFFER dsbuf;
				nResult = ds->CreateSoundBuffer(&m_dsBufDesc, &dsbuf, NULL);
				if (nResult == DS_OK) {
					nResult = dsbuf->SetFormat(&m_pcmWf);
					if (nResult == DS_OK) {
						DOUT (_T("SUCCESS: DirectSound created and formatted\n\r"));
					}
					else {
						DOUT(_T("ERROR: Unable to set DirectSound format\n\r"));
						return FALSE;
					}
				m_pDSBuf.push_back(dsbuf);
				}
				else {
					DOUT(_T("ERROR: Unable to create DirectSound buffer\n\r"));
					return FALSE;
				}
			}
			else {
				DOUT(_T("ERROR: Unable to set DirectSound cooperative level\n\r"));
				return FALSE;
			}
			m_pDS.push_back(ds);
		}
		else {
			// Error
			DOUT(_T("ERROR: Unable to create DirectSound object\n\r"));
			return FALSE;
		}
	}
    return TRUE;
}
int DSound_Init(void)
{
    // this function initializes the sound system
    static int first_time = 1; // used to track the first time the function
    // is entered

    // test for very first time
    if (first_time)
    {		
        // clear everything out
        memset(sound_fx,0,sizeof(pcm_sound)*MAX_SOUNDS);

        // reset first time
        first_time = 0;

        // create a directsound object
        if (FAILED(DirectSoundCreate(NULL, &lpds, NULL)))
            return(0);

        // set cooperation level
        if (FAILED(lpds->SetCooperativeLevel((HWND)main_window_handle,DSSCL_NORMAL)))
            return(0);

    } // end if

    // initialize the sound fx array
    for (int index=0; index<MAX_SOUNDS; index++)
    {
        // test if this sound has been loaded
        if (sound_fx[index].dsbuffer)
        {
            // stop the sound
            sound_fx[index].dsbuffer->Stop();

            // release the buffer
            sound_fx[index].dsbuffer->Release();

        } // end if

        // clear the record out
        memset(&sound_fx[index],0,sizeof(pcm_sound));

        // now set up the fields
        sound_fx[index].state = SOUND_NULL;
        sound_fx[index].id    = index;

    } // end for index

    // return sucess
    return(1);

} // end DSound_Init
Exemplo n.º 9
0
int Game_Init(void *parms)
{
// this function is where you do all the initialization 
// for your game

// create a directsound object
if (DirectSoundCreate(NULL, &lpds, NULL)!=DS_OK )
	return(0);

// set cooperation level
if (lpds->SetCooperativeLevel(main_window_handle,DSSCL_NORMAL)!=DS_OK)
	return(0);

// clear array out
memset(sound_fx,0,sizeof(pcm_sound)*MAX_SOUNDS);
	
// initialize the sound fx array
for (int index=0; index<MAX_SOUNDS; index++)
	{
	// test if this sound has been loaded
	if (sound_fx[index].dsbuffer)
		{
		// stop the sound
		sound_fx[index].dsbuffer->Stop();

		// release the buffer
		sound_fx[index].dsbuffer->Release();
	
		} // end if

	// clear the record out
	memset(&sound_fx[index],0,sizeof(pcm_sound));

	// now set up the fields
	sound_fx[index].state = SOUND_NULL;
	sound_fx[index].id    = index;

	} // end for index

// load a wav file in
if ((sound_id = DSound_Load_WAV("FLIGHT.WAV"))!=-1)
   {
   // start the voc playing in looping mode
   sound_fx[sound_id].dsbuffer->Play(0,0,DSBPLAY_LOOPING);
   } // end if

// return success
return(1);

} // end Game_Init
Exemplo n.º 10
0
bool DirectSoundInitialisation()
{
	const char DirectSoundInitialisationError[] = "Direct Sound Initialisation Error...";
	HRESULT				dsscl;				// SetCooperativeLevel error description.

	if(DirectSoundCreate(NULL, &lpDS, NULL) != DS_OK)
	{
		MessageBox(ghwnd, "DirectSound Initialisation failed!", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	if((dsscl = lpDS->SetCooperativeLevel(ghwnd, DSSCL_NORMAL)) != DS_OK)
	{
		switch(dsscl)
		{
			case DSERR_ALLOCATED:
			{	
				MessageBox(ghwnd, "DirectSound cooperative level setting failed... Resources tied up.", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
				break;
			}
			case DSERR_INVALIDPARAM:
			{
				MessageBox(ghwnd, "DirectSound cooperative level setting failed... Invalid parameter passed.", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
				break;
			}
			case DSERR_UNINITIALIZED:
			{
				MessageBox(ghwnd, "DirectSound cooperative level setting failed... IDirectSound::Initialize not called.", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
				break;
			}
			case DSERR_UNSUPPORTED:
			{
				MessageBox(ghwnd, "DirectSound cooperative level setting failed... Function not supported.", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
				break;
			}
			default:
				break;
		}

			return false;
	}

	if(!load_sounds())
	{
		MessageBox(ghwnd, "Sound file loading for DirectSound failed!", DirectSoundInitialisationError, MB_OK | MB_ICONEXCLAMATION);
		return false;
	}

	return true;
}
Exemplo n.º 11
0
//-----------------------------------------------------------------------------
// Name: DSUtil_InitDirectSound()
// Desc: 
//-----------------------------------------------------------------------------
HRESULT DSUtil_InitDirectSound( HWND hWnd )
{
    if( FAILED( DirectSoundCreate( NULL, &g_pDS, NULL ) ) )
        return E_FAIL;

    if( FAILED( g_pDS->SetCooperativeLevel( hWnd, DSSCL_NORMAL ) ) )
    {
        g_pDS->Release();
        g_pDS = NULL;
        return E_FAIL;
    }

    return S_OK;
}
Exemplo n.º 12
0
/*
=================
SNDDMA_Activate

When we change windows we need to do this
=================
*/
void SNDDMA_Activate( qboolean bAppActive )
{
	if (s_UseOpenAL)
	{
		S_AL_MuteAllSounds(!bAppActive);
	}

	if ( !pDS ) {
		return;
	}

	if ( DS_OK != pDS->SetCooperativeLevel( g_wv.hWnd, DSSCL_PRIORITY ) )	{
		Com_Printf ("sound SetCooperativeLevel failed\n");
		SNDDMA_Shutdown ();
	}
}
Exemplo n.º 13
0
/*
==================
SNDDMA_Shutdown
==================
*/
void SNDDMA_Shutdown( void ) {
	Com_DPrintf( "Shutting down sound system\n" );

	if ( pDS ) {
		Com_DPrintf( "Destroying DS buffers\n" );
		if ( pDS )
		{
			Com_DPrintf( "...setting NORMAL coop level\n" );
			// FIXME JA was DSSCL_NORMAL and Q3 says DSSCL_PRIORITY but the printf says setting normal
			pDS->SetCooperativeLevel( g_wv.hWnd, DSSCL_PRIORITY );
		}

		if ( pDSBuf )
		{
			Com_DPrintf( "...stopping and releasing sound buffer\n" );
			pDSBuf->Stop( );
			pDSBuf->Release( );
		}

		// only release primary buffer if it's not also the mixing buffer we just released
		if ( pDSPBuf && ( pDSBuf != pDSPBuf ) )
		{
			Com_DPrintf( "...releasing primary buffer\n" );
			pDSPBuf->Release( );
		}
		pDSBuf = NULL;
		pDSPBuf = NULL;

		dma.buffer = NULL;

		Com_DPrintf( "...releasing DS object\n" );
		pDS->Release( );
	}

	if ( hInstDS ) {
		Com_DPrintf( "...freeing DSOUND.DLL\n" );
		FreeLibrary( hInstDS );
		hInstDS = NULL;
	}

	pDS = NULL;
	pDSBuf = NULL;
	pDSPBuf = NULL;
	dsound_init = qfalse;
	memset ((void *)&dma, 0, sizeof (dma));
	CoUninitialize( );
}
Exemplo n.º 14
0
int DSInit(HWND hwnd)
{
    static int first_time = 1; // used to track the first time the function is entered
    int index;
    
    // test for very first time
    if (first_time) {
        // clear everything out
        memset(sound_fx, 0, sizeof(PCMSOUND) * MAX_SOUNDS);
        
        // reset first time
        first_time = 0;
        
        // create a directsound object
        if (DirectSoundCreate(NULL, &lpDS, NULL) != DS_OK) {
            return(0);
        }
        
        // set cooperation level
        if (lpDS->SetCooperativeLevel(hwnd, DSSCL_NORMAL) != DS_OK) {
            return(0);
        }
    }
    
    // initialize the sound fx array
    for (index = 0; index < MAX_SOUNDS; index++) {
        // test if this sound has been loaded
        if (sound_fx[index].dsbuffer) {
            // stop the sound
            sound_fx[index].dsbuffer->Stop();
            // release the buffer
            sound_fx[index].dsbuffer->Release();
        }
        
        // clear the record out
        memset(&sound_fx[index], 0, sizeof(PCMSOUND));
        
        // now set up the fields
        sound_fx[index].dsbuffer = NULL;
        sound_fx[index].state = SOUND_NULL;
        sound_fx[index].id    = index;
    }
    
    // return sucess
    return(1);
}
Exemplo n.º 15
0
BOOL LC3Sound::AppCreateWritePrimaryBuffer(
    LPDIRECTSOUND lpDirectSound,
    LPDIRECTSOUNDBUFFER *lplpDsb,
    HWND hwnd)
{
    DSBUFFERDESC dsbdesc;
    HRESULT hr;
    WAVEFORMATEX pcmwf;

    // Set up wave format structure.
    memset(&pcmwf, 0, sizeof(WAVEFORMATEX));
    pcmwf.wFormatTag 		= WAVE_FORMAT_PCM;
    
    pcmwf.nChannels = 1;
    pcmwf.nSamplesPerSec		= 22050;
    pcmwf.wBitsPerSample		= 8;
    pcmwf.nBlockAlign			= pcmwf.nChannels * (pcmwf.wBitsPerSample/8);
    pcmwf.nAvgBytesPerSec		= pcmwf.nSamplesPerSec * pcmwf.nBlockAlign;
    
    // Set up DSBUFFERDESC structure.
    memset(&dsbdesc, 0, sizeof(DSBUFFERDESC)); // Zero it out.
    dsbdesc.dwSize = sizeof(DSBUFFERDESC);
    dsbdesc.dwFlags = DSBCAPS_PRIMARYBUFFER;	//;	//DSBCAPS_GLOBALFOCUS;	//;
    dsbdesc.dwBufferBytes = 0; // Buffer size is determined
                               // by sound hardware.
    dsbdesc.lpwfxFormat = NULL; // Must be NULL for primary buffers.
    // Obtain write-primary cooperative level.
    hr = lpDirectSound->SetCooperativeLevel(hwnd, DSSCL_PRIORITY);
    if(DS_OK == hr)
    {
        // Succeeded! Try to create buffer.
        hr = lpDirectSound->CreateSoundBuffer(
            &dsbdesc, lplpDsb, NULL);
        if(DS_OK == hr) {
            // Succeeded! Set primary buffer to desired format.
            hr = (*lplpDsb)->SetFormat(&pcmwf);
            (*lplpDsb)->Play(0, 0, DSBPLAY_LOOPING);
            return TRUE;
        }
    }
    // If we got here, then we failed SetCooperativeLevel.
    // CreateSoundBuffer, or SetFormat.
    *lplpDsb = NULL;
    return FALSE;
}
Exemplo n.º 16
0
// DirectSound-Objekte initialisieren
int InitDSound(HWND hWnd)
{
	HRESULT dsrval;
	// 1. Schritt: DirectSound Interface erstellen
	dsrval = DirectSoundCreate(NULL, &lpDS, NULL);
	if(FAILED(dsrval))
	{
		MessageBox(NULL, "Error", "DirectSoundCreate()", NULL);
		return 1;
	}
	// 2. Schritt: Coop-Level festlegen
	dsrval = lpDS->SetCooperativeLevel(hWnd, DSSCL_NORMAL);
	if(FAILED(dsrval))
	{
		MessageBox(NULL, "Error", "SetCooperativeLevel()", NULL);
		return 1;
	}
	return 0;
}
Exemplo n.º 17
0
bool AudioOutputDSoundPrivate::init()
{
    if (!loadDll())
        return false;
    typedef HRESULT (WINAPI *DirectSoundCreateFunc)(LPGUID, LPDIRECTSOUND *, LPUNKNOWN);
    //typedef HRESULT (WINAPI *DirectSoundEnumerateFunc)(LPDSENUMCALLBACKA, LPVOID);
    DirectSoundCreateFunc dsound_create = (DirectSoundCreateFunc)GetProcAddress(dll, "DirectSoundCreate");
    //DirectSoundEnumerateFunc dsound_enumerate = (DirectSoundEnumerateFunc)GetProcAddress(dll, "DirectSoundEnumerateA");
    if (!dsound_create) {
        qWarning("Failed to resolve 'DirectSoundCreate'");
        unloadDll();
        return false;
    }
    if (FAILED(dsound_create(NULL/*dev guid*/, &dsound, NULL))){
        unloadDll();
        return false;
    }
    /*  DSSCL_EXCLUSIVE: can modify the settings of the primary buffer, only the sound of this app will be hearable when it will have the focus.
     */
    if (FAILED(dsound->SetCooperativeLevel(GetDesktopWindow(), DSSCL_EXCLUSIVE))) {
        qWarning("Cannot set direct sound cooperative level");
        SafeRelease(&dsound);
        return false;
    }
    qDebug("DirectSound initialized.");
    DSCAPS dscaps;
    memset(&dscaps, 0, sizeof(DSCAPS));
    dscaps.dwSize = sizeof(DSCAPS);
    if (FAILED(dsound->GetCaps(&dscaps))) {
       qWarning("Cannot get device capabilities.");
       SafeRelease(&dsound);
       return false;
    }
    if (dscaps.dwFlags & DSCAPS_EMULDRIVER)
        qDebug("DirectSound is emulated");

    write_offset = 0;
    return true;
}
Exemplo n.º 18
0
static int Initialize(void *hwnd)
{
    DSBUFFERDESC primaryDesc;
    if (!g_lpDSDevice) return TRUE;
    sysMemZero(&primaryDesc, sizeof(DSBUFFERDESC));
    primaryDesc.dwSize = sizeof(DSBUFFERDESC);
    primaryDesc.dwFlags = DSBCAPS_PRIMARYBUFFER;
    if (RLX.Audio.Config & RLXAUDIO_Use3D)
		primaryDesc.dwFlags|= DSBCAPS_CTRL3D;

	if (SYS_DXTRACE(g_lpDSDevice->SetCooperativeLevel((HWND)hwnd, DSSCL_EXCLUSIVE)) != DS_OK)
		return -1;

	if (SYS_DXTRACE(g_lpDSDevice->CreateSoundBuffer(&primaryDesc, &g_lpPrimaryBuffer, NULL))!=DS_OK )
		return 0;
    else
    {
		HRESULT hr;
		sysMemZero(&g_cDSPCMOutFormat, sizeof(WAVEFORMATEX));
		g_cDSPCMOutFormat.wFormatTag = WAVE_FORMAT_PCM;
		g_cDSPCMOutFormat.wBitsPerSample = 16;
		g_cDSPCMOutFormat.nChannels = 2;
		g_cDSPCMOutFormat.nSamplesPerSec = 44100;
		g_cDSPCMOutFormat.nBlockAlign = (uint16_t)(g_cDSPCMOutFormat.nChannels   *  (g_cDSPCMOutFormat.wBitsPerSample>>3));
		g_cDSPCMOutFormat.nAvgBytesPerSec = (uint32_t)g_cDSPCMOutFormat.nBlockAlign *  (uint32_t)g_cDSPCMOutFormat.nSamplesPerSec;
		hr = g_lpPrimaryBuffer->SetFormat(&g_cDSPCMOutFormat);
		if ( hr != DS_OK )
			FindAlternateSampleFormat();

        if (RLX.Audio.Config & RLXAUDIO_Use3D)
        {
			hr = SYS_DXTRACE(g_lpPrimaryBuffer->QueryInterface(IID_IDirectSound3DListener, (void**)&g_lpDS3DListener));
            if (hr== DS_OK)
				hr = g_lpDS3DListener->SetAllParameters(&Listener3dProps, DS3D_IMMEDIATE);
        }
    }
    return 0; // no problemo.
}
Exemplo n.º 19
0
internal void
Win32InitDSound(HWND Window, int32 BufferSize, int32 SamplesPerSecond) {
   //Load library, get directsound object, create primary buffer, create secondary buffer
   // start playing!

   HMODULE DSoundLibrary = LoadLibraryA("dsound.dll");

   if (DSoundLibrary) {
      direct_sound_create *DirectSoundCreate = (direct_sound_create *)
         GetProcAddress(DSoundLibrary, "DirectSoundCreate");

      LPDIRECTSOUND DirectSound;
      if (DirectSoundCreate && SUCCEEDED(DirectSoundCreate(0, &DirectSound, 0))) {

         WAVEFORMATEX WaveFormat = {};
         WaveFormat.wFormatTag = WAVE_FORMAT_PCM;
         WaveFormat.nChannels = 2;
         WaveFormat.wBitsPerSample = 16;
         WaveFormat.nBlockAlign = (WaveFormat.nChannels * WaveFormat.wBitsPerSample) / 8;
         WaveFormat.nSamplesPerSec = SamplesPerSecond;
         WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec * WaveFormat.nBlockAlign;
         WaveFormat.cbSize = 0;

         if (SUCCEEDED(DirectSound->SetCooperativeLevel(Window, DSSCL_PRIORITY))) {

            DSBUFFERDESC BufferDescription = {};
            BufferDescription.dwBufferBytes = sizeof(BufferDescription);
            BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;

            LPDIRECTSOUNDBUFFER PrimaryBuffer;
            if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0))) {

               if (SUCCEEDED(PrimaryBuffer->SetFormat(&WaveFormat))) {

               }
               else {
                  //Log!
               }
            }
            else {
               //Log!
            }
         }
         else {
            //Log this!
         }

         DSBUFFERDESC BufferDescription = {};
         BufferDescription.dwSize = sizeof(BufferDescription);
         BufferDescription.dwFlags = 0;
         BufferDescription.dwBufferBytes = BufferSize;
         BufferDescription.lpwfxFormat = &WaveFormat;

         if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0))) {
         
         }
         else {
            //Log!
         }
      }
      else {
         //log error
      }
   }
   else {

   }
}
Exemplo n.º 20
0
internal void Win32InitDSound(HWND Window, int32 SamplesPerSecond, int32 BufferSize)
{
	HMODULE DSoundLibrary = LoadLibraryA("dsound.dll");
	if (DSoundLibrary)
	{
		direct_sound_create *DirectSoundCreate = (direct_sound_create *)GetProcAddress(DSoundLibrary, "DirectSoundCreate");

		// TODO: Double-check that this works on XP - DirectSound8 or 7??
		LPDIRECTSOUND DirectSound;
		if (DirectSoundCreate && SUCCEEDED(DirectSoundCreate(0, &DirectSound, 0)))
		{
			WAVEFORMATEX WaveFormat    = {};
			WaveFormat.wFormatTag      = WAVE_FORMAT_PCM;
			WaveFormat.nChannels       = 2;
			WaveFormat.nSamplesPerSec  = SamplesPerSecond;
			WaveFormat.wBitsPerSample  = 16;
			WaveFormat.nBlockAlign     = (WaveFormat.nChannels*WaveFormat.wBitsPerSample) / 8;
			WaveFormat.nAvgBytesPerSec = WaveFormat.nSamplesPerSec*WaveFormat.nBlockAlign;
			WaveFormat.cbSize          = 0;

			if (SUCCEEDED(DirectSound->SetCooperativeLevel(Window, DSSCL_PRIORITY)))
			{
				DSBUFFERDESC BufferDescription = {};
				BufferDescription.dwSize       = sizeof(BufferDescription);
				BufferDescription.dwFlags      = DSBCAPS_PRIMARYBUFFER;

				// NOTE: "Create" a primary buffer
				// TODO: DSBCAPS_GLOBALFOCUS?
				LPDIRECTSOUNDBUFFER PrimaryBuffer;
				if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0)))
				{
					HRESULT Error = PrimaryBuffer->SetFormat(&WaveFormat);
					if (SUCCEEDED(Error))
					{
						// NOTE: We have finally set the format!
						OutputDebugStringA("Primary buffer format was set.\n");
					}
					else
					{
						// TODO: Diagnostic
					}
				}
				else
				{
					// TODO: Diagnostic
				}
			}
			else
			{
				// TODO: Diagnostic
			}

			// TODO: DSBCAPS_GETCURRENTPOSITION2
			DSBUFFERDESC BufferDescription  = {};
			BufferDescription.dwSize        = sizeof(BufferDescription);
			BufferDescription.dwFlags       = 0;
			BufferDescription.dwBufferBytes = BufferSize;
			BufferDescription.lpwfxFormat   = &WaveFormat;
			HRESULT Error = DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0);
			if (SUCCEEDED(Error))
			{
				OutputDebugStringA("Secondary buffer created successfully.\n");
			}
		}
		else
		{
			// TODO: Diagnostic
		}
	}
	else
	{
		// TODO: Diagnostic
	}
}
Exemplo n.º 21
0
bool nuiAudioDevice_DirectSound::Open(std::vector<uint32>& rInputChannels, std::vector<uint32>& rOutputChannels, double SampleRate, uint32 BufferSize, nuiAudioProcessFn pProcessFunction)
{
  if (!mpDirectSound)
    return false;
  
  HRESULT hr = S_OK;
  mAudioProcessFn = pProcessFunction;

  mBufferSize = BufferSize;

  hr = mpDirectSound->SetCooperativeLevel(GetDesktopWindow(), DSSCL_EXCLUSIVE);

  mHasInput = (rInputChannels.size() > 0) && (mInputChannels.size() > 0);
  mHasOutput = (rOutputChannels.size() > 0) && (mOutputChannels.size() > 0);


  mpInputBuffer = NULL;
  mpOutputBuffer = NULL;

  if (!mHasInput && !mHasOutput)
    return false;

  // init ringbuffer
  mpRingBuffer = new nglRingBuffer(BufferSize*4, sizeof(float), rOutputChannels.size());
  mpRingBuffer->AdvanceWriteIndex(BufferSize);

  // init input buffers
  if (mHasInput)
  {
    {
      mActiveInputChannels = rInputChannels;
    }

    WAVEFORMATEX IFormat;
    IFormat.wFormatTag = WAVE_FORMAT_PCM;
    IFormat.nChannels = (WORD)mInputChannels.size();
    IFormat.nSamplesPerSec = ToNearest(SampleRate);
    IFormat.wBitsPerSample = 16;
    IFormat.nAvgBytesPerSec = IFormat.nChannels * IFormat.nSamplesPerSec * (IFormat.wBitsPerSample / 8);
    IFormat.nBlockAlign = IFormat.nChannels * (IFormat.wBitsPerSample / 8);
    IFormat.cbSize = 0;

    DSCBUFFERDESC IBufferDesc;
    memset(&IBufferDesc, 0, sizeof(IBufferDesc));
    IBufferDesc.dwSize = sizeof(DSCBUFFERDESC);
    IBufferDesc.dwFlags = DSCBCAPS_WAVEMAPPED;
    IBufferDesc.dwBufferBytes = (IFormat.wBitsPerSample / 8) * IFormat.nChannels * BufferSize * 2;
    IBufferDesc.dwReserved = 0;
    IBufferDesc.lpwfxFormat = &IFormat;
    IBufferDesc.dwFXCount = 0;
    IBufferDesc.lpDSCFXDesc = NULL;

    NGL_ASSERT(mpDirectSoundCapture);
    hr = mpDirectSoundCapture->CreateCaptureBuffer(&IBufferDesc, &mpInputBuffer, NULL);
  }


  // init output buffers
  if (mHasOutput)
  {
    {
      mActiveOutputChannels = rOutputChannels;
    }

    WAVEFORMATEX OFormat;
    OFormat.wFormatTag = WAVE_FORMAT_PCM;
    OFormat.nChannels = (WORD)mOutputChannels.size();
    OFormat.nSamplesPerSec = ToNearest(SampleRate);
    OFormat.wBitsPerSample = 16;
    OFormat.nAvgBytesPerSec = OFormat.nChannels * OFormat.nSamplesPerSec * (OFormat.wBitsPerSample / 8);
    OFormat.nBlockAlign = OFormat.nChannels * OFormat.wBitsPerSample / 8;
    OFormat.cbSize = 0;

    DSBUFFERDESC  OBufferDesc;
    memset(&OBufferDesc, 0, sizeof(OBufferDesc));
    OBufferDesc.dwSize = sizeof(OBufferDesc);
    OBufferDesc.dwFlags = DSBCAPS_GLOBALFOCUS | DSBCAPS_CTRLPOSITIONNOTIFY;
    OBufferDesc.dwBufferBytes = (OFormat.wBitsPerSample / 8) * OFormat.nChannels * BufferSize * 2;
    OBufferDesc.dwReserved = 0;
    OBufferDesc.lpwfxFormat = &OFormat;

    hr = mpDirectSound->CreateSoundBuffer(&OBufferDesc, &mpOutputBuffer, NULL);
  }


  // create event for notifications
  mNotifInputEvent[0] = CreateEvent(NULL, FALSE, FALSE, _T("NUI_DSoundInputEvent0"));
  mNotifInputEvent[1] = CreateEvent(NULL, FALSE, FALSE, _T("NUI_DSoundInputEvent1"));
  mNotifOutputEvent[0] = CreateEvent(NULL, FALSE, FALSE, _T("NUI_DSoundOutputEvent0"));
  mNotifOutputEvent[1] = CreateEvent(NULL, FALSE, FALSE, _T("NUI_DSoundOutputEvent1"));




  // set the notification for the input buffer
  if (mHasInput)
  {
    // Setup the notification positions
    ZeroMemory( &mInputPosNotify, sizeof(DSBPOSITIONNOTIFY) * 2);
    mInputPosNotify[0].dwOffset = BufferSize * sizeof(int16) * mInputChannels.size() - 1;
    mInputPosNotify[0].hEventNotify = mNotifInputEvent[0];             
    mInputPosNotify[1].dwOffset = BufferSize * sizeof(int16) * mInputChannels.size() * 2 - 1;
    mInputPosNotify[1].hEventNotify = mNotifInputEvent[1];           

    LPDIRECTSOUNDNOTIFY pInputNotify = NULL;
    if( FAILED( hr = mpInputBuffer->QueryInterface( IID_IDirectSoundNotify, (VOID**)&pInputNotify ) ) )
    {
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("Open ERROR : failed in querying interface for input notifications.\n"));
      return false;
    }


    // Tell DirectSound when to notify us. the notification will come in the from 
    // of signaled events that are handled in WinMain()
    if( FAILED( hr = pInputNotify->SetNotificationPositions( 2, mInputPosNotify ) ) )
    {
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("Open ERROR : failed in setting notifications for input\n"));
      return false;
    }

    pInputNotify->Release();
  }



  // set the notification events for the output buffer
  if (mHasOutput)
  {
    // Setup the notification positions
    ZeroMemory( &mOutputPosNotify, sizeof(DSBPOSITIONNOTIFY) * 2);
    mOutputPosNotify[0].dwOffset = BufferSize * sizeof(int16) * mOutputChannels.size() - 1;
    mOutputPosNotify[0].hEventNotify = mNotifOutputEvent[0];             
    mOutputPosNotify[1].dwOffset = BufferSize * sizeof(int16) * mOutputChannels.size() * 2 - 1;
    mOutputPosNotify[1].hEventNotify = mNotifOutputEvent[1];    

    LPDIRECTSOUNDNOTIFY pOutputNotify = NULL;
    if( FAILED( hr = mpOutputBuffer->QueryInterface( IID_IDirectSoundNotify, (VOID**)&pOutputNotify ) ) )
    {
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("Open ERROR : failed in querying interface for output notifications.\n"));
      return false;
    }

    // Tell DirectSound when to notify us. the notification will come in the from 
    // of signaled events that are handled in WinMain()
    if( FAILED( hr = pOutputNotify->SetNotificationPositions( 2, mOutputPosNotify ) ) )
    {
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("Open ERROR : failed in setting notifications for output\n"));
      return false;
    }

    pOutputNotify->Release();
  }


  // start input processing thread
  mpProcessingTh = new nuiAudioDevice_DS_ProcessingTh(this, mNotifInputEvent[0], mNotifInputEvent[1], mAudioProcessFn);
  mpProcessingTh->Start();



  // start output thread
  if (mHasOutput)
  {
    mpOutputTh = new nuiAudioDevice_DS_OutputTh(this, mNotifInputEvent[0], mNotifInputEvent[1], mNotifOutputEvent[0], mNotifOutputEvent[1]);
    mpOutputTh->Start();
    hr = mpOutputBuffer->Play(0,0,DSCBSTART_LOOPING);
    if (FAILED(hr))
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("OutputBuffer->Play ERROR!\n"));
  }

  // start input capture
  if (mHasInput)
  {
    hr = mpInputBuffer->Start(DSCBSTART_LOOPING);
    if (FAILED(hr))
      NGL_LOG(_T("nuiAudioDevice_DirectSound"), NGL_LOG_ERROR, _T("InputBuffer->Start ERROR!\n"));    
  }





  return true;
}
Exemplo n.º 22
0
internal void Win32InitDSound(HWND _Window, int32 _SamplerPerSecond, int32 _SecondaryBufferSize)
{
    // NOTE: Load the Library
    HMODULE dSoundLibrary = LoadLibraryA("dsound.dll");
    if (dSoundLibrary)
    {
        // NOTE: Get a DirectSound  object!
        direct_sound_create* directSoundCreate = (direct_sound_create*)
            GetProcAddress(dSoundLibrary, "DirectSoundCreate");

        LPDIRECTSOUND directSound;
        if (directSoundCreate && SUCCEEDED(directSoundCreate(0, &directSound, 0)))
        {
            WAVEFORMATEX waveFormat = {};
            waveFormat.wFormatTag = WAVE_FORMAT_PCM;
            waveFormat.nChannels = 2;
            waveFormat.nSamplesPerSec = _SamplerPerSecond;
            waveFormat.wBitsPerSample = 16;
            waveFormat.nBlockAlign = (waveFormat.nChannels * waveFormat.wBitsPerSample) / 8;
            waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign;
            waveFormat.cbSize = 0;

            if (SUCCEEDED(directSound->SetCooperativeLevel(_Window, DSSCL_PRIORITY)))
            {
                DSBUFFERDESC bufferDescription = {};
                bufferDescription.dwSize = sizeof(bufferDescription);
                bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;

                LPDIRECTSOUNDBUFFER primaryBuffer;
                if (SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &primaryBuffer, 0)))
                {
                    HRESULT error = primaryBuffer->SetFormat(&waveFormat);
                    if (SUCCEEDED(error))
                    {
                        OutputDebugStringA("primary buffer format was set.\n");
                    }
                    else
                    {

                    }
                }
                else
                {

                }
            }
            else
            {

            }

            DSBUFFERDESC bufferDescription = {};
            bufferDescription.dwSize = sizeof(bufferDescription);
            bufferDescription.dwFlags = 0;
            bufferDescription.dwBufferBytes = _SecondaryBufferSize;
            bufferDescription.lpwfxFormat = &waveFormat;
            HRESULT error = directSound->CreateSoundBuffer(&bufferDescription, &GlobalSecondaryBuffer, 0); 
            if (SUCCEEDED(error))
            {
                OutputDebugStringA("Secondary buffer created successfully.\n");
            }
        }
        else
        {

        }
    }
    else
    {

    }
}
Exemplo n.º 23
0
internal void initDirectSound(HWND windowHandle, int32 samplePerSecond, int32 bufferSize) {
	// Load the library
	HMODULE directSoundLibrary = LoadLibraryA("dsound.dll");
	if ( ! directSoundLibrary ) {
		OutputDebugStringA("Direct sound dll not found ");
		return;
	}

	// Get a direct sound object
	direct_sound_create *directSoundCreate = (direct_sound_create*)GetProcAddress(directSoundLibrary, "DirectSoundCreate");

	HRESULT error;

	LPDIRECTSOUND directSound;
	error = directSoundCreate(0, &directSound, 0);
	if ( directSoundCreate && SUCCEEDED(error) ) {

		DSBUFFERDESC bufferDescription = {};
		bufferDescription.dwSize = sizeof(bufferDescription);
		bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;

		WAVEFORMATEX waveFormat = {};
		waveFormat.wFormatTag = WAVE_FORMAT_PCM;
		waveFormat.nChannels = 2;
		waveFormat.nSamplesPerSec = samplePerSecond;
		waveFormat.wBitsPerSample = 16;
		waveFormat.nBlockAlign = (waveFormat.nChannels*waveFormat.wBitsPerSample) / 8;
		waveFormat.nAvgBytesPerSec = waveFormat.nSamplesPerSec * waveFormat.nBlockAlign; 
		waveFormat.cbSize = 0;

		

		LPDIRECTSOUNDBUFFER primaryBuffer;
		// create a primary buffer
		
		if ( SUCCEEDED(directSound->SetCooperativeLevel(windowHandle, DSSCL_PRIORITY)) ) {

			if ( SUCCEEDED(error = directSound->CreateSoundBuffer(&bufferDescription, &primaryBuffer, 0)) ) {
				
				if ( !(SUCCEEDED(error = primaryBuffer->SetFormat(&waveFormat))) ) {
					OutputDebugStringA("Primary buffer failed " + error );
				}

			} else {
				OutputDebugStringA("Primary buffer failed " + error);
			}

			DSBUFFERDESC bufferDescription = {};
			bufferDescription.dwSize = sizeof(bufferDescription);
			bufferDescription.dwFlags = 0;
			bufferDescription.dwBufferBytes = bufferSize;
			bufferDescription.lpwfxFormat = &waveFormat;

			
			// create a secondary buffer
			if ( SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &globalSecondaryBuffer, 0)) ) {

			}
		}

		

		// start playing it
	}
	else {
		OutputDebugStringA("Create DSound error " + error);
	}

	

}
Exemplo n.º 24
0
HRESULT sound_direct_sound::dsound_init()
{
	assert(!m_dsound);
	HRESULT result;

	// create the DirectSound object
	result = DirectSoundCreate(nullptr, &m_dsound, nullptr);
	if (result != DS_OK)
	{
		osd_printf_error("Error creating DirectSound: %08x\n", (unsigned)result);
		goto error;
	}

	// get the capabilities
	DSCAPS dsound_caps;
	dsound_caps.dwSize = sizeof(dsound_caps);
	result = m_dsound->GetCaps(&dsound_caps);
	if (result != DS_OK)
	{
		osd_printf_error("Error getting DirectSound capabilities: %08x\n", (unsigned)result);
		goto error;
	}

	// set the cooperative level
	{
#ifdef SDLMAME_WIN32
		SDL_SysWMinfo wminfo;
		SDL_VERSION(&wminfo.version);
		SDL_GetWindowWMInfo(osd_common_t::s_window_list.front()->platform_window<SDL_Window*>(), &wminfo);
		HWND const window = wminfo.info.win.window;
#else // SDLMAME_WIN32
		HWND const window = osd_common_t::s_window_list.front()->platform_window<HWND>();
#endif // SDLMAME_WIN32
		result = m_dsound->SetCooperativeLevel(window, DSSCL_PRIORITY);
	}
	if (result != DS_OK)
	{
		osd_printf_error("Error setting DirectSound cooperative level: %08x\n", (unsigned)result);
		goto error;
	}

	{
		// make a format description for what we want
		WAVEFORMATEX stream_format;
		stream_format.wBitsPerSample    = 16;
		stream_format.wFormatTag        = WAVE_FORMAT_PCM;
		stream_format.nChannels         = 2;
		stream_format.nSamplesPerSec    = sample_rate();
		stream_format.nBlockAlign       = stream_format.wBitsPerSample * stream_format.nChannels / 8;
		stream_format.nAvgBytesPerSec   = stream_format.nSamplesPerSec * stream_format.nBlockAlign;

		// compute the buffer size based on the output sample rate
		DWORD stream_buffer_size = stream_format.nSamplesPerSec * stream_format.nBlockAlign * m_audio_latency / 10;
		stream_buffer_size = std::max(DWORD(1024), (stream_buffer_size / 1024) * 1024);

		LOG(("stream_buffer_size = %u\n", (unsigned)stream_buffer_size));

		// create the buffers
		m_bytes_per_sample = stream_format.nBlockAlign;
		m_stream_buffer_in = 0;
		result = create_buffers(stream_buffer_size, stream_format);
		if (result != DS_OK)
			goto error;
	}

	// start playing
	result = m_stream_buffer.play_looping();
	if (result != DS_OK)
	{
		osd_printf_error("Error playing: %08x\n", (UINT32)result);
		goto error;
	}
	return DS_OK;

	// error handling
error:
	destroy_buffers();
	dsound_kill();
	return result;
}
Exemplo n.º 25
0
/*
===============
idAudioHardwareWIN32::SetPrimaryBufferFormat
Set primary buffer to a specified format
For example, to set the primary buffer format to 22kHz stereo, 16-bit
then:   dwPrimaryChannels = 2
        dwPrimaryFreq     = 22050,
        dwPrimaryBitRate  = 16
===============
*/
void idAudioHardwareWIN32::SetPrimaryBufferFormat(dword dwPrimaryFreq, dword dwPrimaryBitRate, dword dwSpeakers)
{
	HRESULT             hr;

	if (m_pDS == NULL) {
		return;
	}

	ulong cfgSpeakers;
	m_pDS->GetSpeakerConfig(&cfgSpeakers);

	DSCAPS dscaps;
	dscaps.dwSize = sizeof(DSCAPS);
	m_pDS->GetCaps(&dscaps);

	if (dscaps.dwFlags & DSCAPS_EMULDRIVER) {
		return;
	}

	// Get the primary buffer
	DSBUFFERDESC dsbd;
	ZeroMemory(&dsbd, sizeof(DSBUFFERDESC));
	dsbd.dwSize        = sizeof(DSBUFFERDESC);
	dsbd.dwFlags       = DSBCAPS_PRIMARYBUFFER;
	dsbd.dwBufferBytes = 0;
	dsbd.lpwfxFormat   = NULL;

	// Obtain write-primary cooperative level.
	if (FAILED(hr = m_pDS->SetCooperativeLevel(win32.hWnd, DSSCL_PRIORITY))) {
		DXTRACE_ERR(TEXT("SetPrimaryBufferFormat"), hr);
		return;
	}

	if (FAILED(hr = m_pDS->CreateSoundBuffer(&dsbd, &pDSBPrimary, NULL))) {
		return;
	}

	if (dwSpeakers == 6 && (cfgSpeakers == DSSPEAKER_5POINT1 || cfgSpeakers == DSSPEAKER_SURROUND)) {
		WAVEFORMATEXTENSIBLE 	waveFormatPCMEx;
		ZeroMemory(&waveFormatPCMEx, sizeof(WAVEFORMATEXTENSIBLE));

		waveFormatPCMEx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
		waveFormatPCMEx.Format.nChannels = 6;
		waveFormatPCMEx.Format.nSamplesPerSec = dwPrimaryFreq;
		waveFormatPCMEx.Format.wBitsPerSample  = (WORD) dwPrimaryBitRate;
		waveFormatPCMEx.Format.nBlockAlign = waveFormatPCMEx.Format.wBitsPerSample / 8 * waveFormatPCMEx.Format.nChannels;
		waveFormatPCMEx.Format.nAvgBytesPerSec = waveFormatPCMEx.Format.nSamplesPerSec * waveFormatPCMEx.Format.nBlockAlign;
		waveFormatPCMEx.dwChannelMask = KSAUDIO_SPEAKER_5POINT1;
		// SPEAKER_FRONT_LEFT | SPEAKER_FRONT_RIGHT |
		// SPEAKER_FRONT_CENTER | SPEAKER_LOW_FREQUENCY |
		// SPEAKER_BACK_LEFT  | SPEAKER_BACK_RIGHT
		waveFormatPCMEx.SubFormat =  KSDATAFORMAT_SUBTYPE_PCM;  // Specify PCM
		waveFormatPCMEx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE);
		waveFormatPCMEx.Samples.wValidBitsPerSample = 16;

		if (FAILED(hr = pDSBPrimary->SetFormat((WAVEFORMATEX *)&waveFormatPCMEx))) {
			DXTRACE_ERR(TEXT("SetPrimaryBufferFormat"), hr);
			return;
		}

		numSpeakers = 6;		// force it to think 5.1
		blockAlign = waveFormatPCMEx.Format.nBlockAlign;
	} else {
		if (dwSpeakers == 6) {
			common->Printf("sound: hardware reported unable to use multisound, defaulted to stereo\n");
		}

		WAVEFORMATEX wfx;
		ZeroMemory(&wfx, sizeof(WAVEFORMATEX));
		wfx.wFormatTag      = WAVE_FORMAT_PCM;
		wfx.nChannels       = 2;
		wfx.nSamplesPerSec  = dwPrimaryFreq;
		wfx.wBitsPerSample  = (WORD) dwPrimaryBitRate;
		wfx.nBlockAlign     = wfx.wBitsPerSample / 8 * wfx.nChannels;
		wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
		wfx.cbSize = sizeof(WAVEFORMATEX);

		if (FAILED(hr = pDSBPrimary->SetFormat(&wfx))) {
			return;
		}

		numSpeakers = 2;		// force it to think stereo
		blockAlign = wfx.nBlockAlign;
	}

	byte *speakerData;
	bufferSize = MIXBUFFER_SAMPLES * sizeof(word) * numSpeakers * ROOM_SLICES_IN_BUFFER;
	speakerData = (byte *)Mem_Alloc(bufferSize);
	memset(speakerData, 0, bufferSize);

	InitializeSpeakers(speakerData, bufferSize, dwPrimaryFreq, dwPrimaryBitRate, numSpeakers);
}
Exemplo n.º 26
0
HRESULT STDMETHODCALLTYPE DirectSound::SetCooperativeLevel(HWND hwnd, DWORD dwLevel)
{
	return m_ds->SetCooperativeLevel(hwnd, dwLevel);
}
Exemplo n.º 27
0
int DSoundInit(HWND wnd_coop, int rate, int stereo, int seg_samples)
{
  DSBUFFERDESC dsbd;
  WAVEFORMATEX wfx;
  DSBPOSITIONNOTIFY notifies[NSEGS];
  int i;

  memset(&dsbd,0,sizeof(dsbd));
  memset(&wfx,0,sizeof(wfx));

  // Make wave format:
  wfx.wFormatTag=WAVE_FORMAT_PCM;
  wfx.nChannels=stereo ? 2 : 1;
  wfx.nSamplesPerSec=rate;
  wfx.wBitsPerSample=16;

  wfx.nBlockAlign=(WORD)((wfx.nChannels*wfx.wBitsPerSample)>>3);
  wfx.nAvgBytesPerSec=wfx.nBlockAlign*wfx.nSamplesPerSec;

  // Create the DirectSound interface:
  DirectSoundCreate(NULL,&DSound,NULL);
  if (DSound==NULL) return 1;

  LoopSeg = seg_samples * 2;
  if (stereo)
    LoopSeg *= 2;

  LoopLen = LoopSeg * NSEGS;

  DSound->SetCooperativeLevel(wnd_coop, DSSCL_PRIORITY);
  dsbd.dwFlags=DSBCAPS_GLOBALFOCUS;  // Play in background
  dsbd.dwFlags|=DSBCAPS_GETCURRENTPOSITION2|DSBCAPS_CTRLPOSITIONNOTIFY;

  // Create the looping buffer:
  dsbd.dwSize=sizeof(dsbd);
  dsbd.dwBufferBytes=LoopLen;
  dsbd.lpwfxFormat=&wfx;

  DSound->CreateSoundBuffer(&dsbd,&LoopBuffer,NULL);
  if (LoopBuffer==NULL) return 1;

  LoopBuffer->QueryInterface(IID_IDirectSoundNotify, (LPVOID*)&DSoundNotify);
  if (DSoundNotify == NULL) {
    lprintf("QueryInterface(IID_IDirectSoundNotify) failed\n");
    goto out;
  }

  seg_played_event = CreateEvent(NULL, 0, 0, NULL);
  if (seg_played_event == NULL)
    goto out;

  for (i = 0; i < NSEGS; i++) {
    notifies[i].dwOffset = i * LoopSeg;
    notifies[i].hEventNotify = seg_played_event;
  }
  i = DSoundNotify->SetNotificationPositions(NSEGS, notifies);
  if (i != DS_OK) {
    lprintf("SetNotificationPositions failed\n");
    goto out;
  }

out:
  LoopBlank();
  LoopBuffer->Play(0, 0, DSBPLAY_LOOPING);
  return 0;
}
Exemplo n.º 28
0
int Game_Init(void *parms)
{
// this function is where you do all the initialization 
// for your game

// this example does everything: it sets up directsound
// creates a secondary buffer, loads it with a synthesizer
// sine wave and plays it

void 	*audio_ptr_1 = NULL,   // used to lock memory
		*audio_ptr_2 = NULL;

DWORD	dsbstatus;              // status of sound buffer

DWORD	audio_length_1    = 0,  // length of locked memory
		audio_length_2    = 0,
		snd_buffer_length = 64000; // working buffer

// allocate memory for buffer
UCHAR *snd_buffer_ptr = (UCHAR *)malloc(snd_buffer_length);

// we need some data for the buffer, you could load a .VOC or .WAV
// but as an example, lets synthesize the data

// fill buffer with a synthesized 100hz sine wave
for (int index=0; index < (int)snd_buffer_length; index++)
	snd_buffer_ptr[index] = 127*sin(6.28*((float)(index%110))/(float)110);

// note the math, 127 is the scale or amplitude
// 6.28 is to convert to radians
// (index % 110) read below
// we are playing at 11025 hz or 11025 cycles/sec therefore, in 1 sec
// we want 100 cycles of our synthesized sound, thus 11025/100 is approx.
// 110, thus we want the waveform to repeat each 110 clicks of index, so
// normalize to 110


// create a directsound object
if (DirectSoundCreate(NULL, &lpds, NULL)!=DS_OK )
	return(0);

// set cooperation level
if (lpds->SetCooperativeLevel(main_window_handle,DSSCL_NORMAL)!=DS_OK)
	return(0);

// set up the format data structure
memset(&pcmwf, 0, sizeof(WAVEFORMATEX));

pcmwf.wFormatTag	  = WAVE_FORMAT_PCM;
pcmwf.nChannels		  = 1;
pcmwf.nSamplesPerSec  = 11025;
pcmwf.nBlockAlign	  = 1;
pcmwf.nAvgBytesPerSec = pcmwf.nSamplesPerSec * pcmwf.nBlockAlign;
pcmwf.wBitsPerSample  = 8;
pcmwf.cbSize		  = 0;

// create the secondary buffer (no need for a primary)
memset(&dsbd,0,sizeof(DSBUFFERDESC));
dsbd.dwSize			= sizeof(DSBUFFERDESC);
dsbd.dwFlags		= DSBCAPS_CTRLDEFAULT | DSBCAPS_STATIC | DSBCAPS_LOCSOFTWARE;
dsbd.dwBufferBytes	= snd_buffer_length+1;
dsbd.lpwfxFormat	= &pcmwf;

if (lpds->CreateSoundBuffer(&dsbd,&lpdsbsecondary,NULL)!=DS_OK)
	return(0);

// copy data into sound buffer
if (lpdsbsecondary->Lock(0,					 
					  snd_buffer_length,			
    				  &audio_ptr_1, 
					  &audio_length_1,
					  &audio_ptr_2, 
					  &audio_length_2,
					  DSBLOCK_FROMWRITECURSOR)!=DS_OK)
  return(0);

// copy first section of circular buffer
CopyMemory(audio_ptr_1, snd_buffer_ptr, audio_length_1);

// copy last section of circular buffer
CopyMemory(audio_ptr_2, (snd_buffer_ptr+audio_length_1),audio_length_2);

// unlock the buffer
if (lpdsbsecondary->Unlock(audio_ptr_1, 
						   audio_length_1, 
						   audio_ptr_2, 
						   audio_length_2)!=DS_OK)
	return(0);

// play the sound in looping mode
if (lpdsbsecondary->Play(0,0,DSBPLAY_LOOPING )!=DS_OK)
	return(0);

// release the memory since DirectSound has made a copy of it
free(snd_buffer_ptr);

// return success
return(1);

} // end Game_Init
Exemplo n.º 29
0
int SNDDMA_InitDS ()
{
	HRESULT			hresult;
	DSBUFFERDESC	dsbuf;
	DSBCAPS			dsbcaps;
	WAVEFORMATEX	format;
	int				use8;

	Com_Printf( "Initializing DirectSound\n");

	use8 = 1;
    // Create IDirectSound using the primary sound device
    if( FAILED( hresult = CoCreateInstance(CLSID_DirectSound8, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound8, (void **)&pDS))) {
		use8 = 0;
	    if( FAILED( hresult = CoCreateInstance(CLSID_DirectSound, NULL, CLSCTX_INPROC_SERVER, IID_IDirectSound, (void **)&pDS))) {
			Com_Printf ("failed\n");
			SNDDMA_Shutdown ();
			return qfalse;
		}
	}

	hresult = pDS->Initialize( NULL);

	Com_DPrintf( "ok\n" );

	Com_DPrintf("...setting DSSCL_PRIORITY coop level: " );

	if ( DS_OK != pDS->SetCooperativeLevel( g_wv.hWnd, DSSCL_PRIORITY ) )	{
		Com_Printf ("failed\n");
		SNDDMA_Shutdown ();
		return qfalse;
	}
	Com_DPrintf("ok\n" );


	// create the secondary buffer we'll actually work with
	dma.channels = 2;
	dma.samplebits = 16;

	if (s_khz->integer == 44)
		dma.speed = 44100;
	else if (s_khz->integer == 22)
		dma.speed = 22050;
	else
		dma.speed = 11025;

	memset (&format, 0, sizeof(format));
	format.wFormatTag = WAVE_FORMAT_PCM;
    format.nChannels = dma.channels;
    format.wBitsPerSample = dma.samplebits;
    format.nSamplesPerSec = dma.speed;
    format.nBlockAlign = format.nChannels * format.wBitsPerSample / 8;
    format.cbSize = 0;
    format.nAvgBytesPerSec = format.nSamplesPerSec*format.nBlockAlign; 

	memset (&dsbuf, 0, sizeof(dsbuf));
	dsbuf.dwSize = sizeof(DSBUFFERDESC);

	// Micah: take advantage of 2D hardware.if available.
	dsbuf.dwFlags = DSBCAPS_CTRLFREQUENCY | DSBCAPS_LOCHARDWARE;
	if (use8) {
		dsbuf.dwFlags |= DSBCAPS_GETCURRENTPOSITION2;
	}
//#define idDSBCAPS_GETCURRENTPOSITION2 0x00010000
	dsbuf.dwBufferBytes = SECONDARY_BUFFER_SIZE;
	dsbuf.lpwfxFormat = &format;
	
	memset(&dsbcaps, 0, sizeof(dsbcaps));
	dsbcaps.dwSize = sizeof(dsbcaps);
	
	Com_DPrintf( "...creating secondary buffer: " );
	if (DS_OK == pDS->CreateSoundBuffer(&dsbuf, &pDSBuf, NULL)) {
		Com_Printf( "locked hardware.  ok\n" );
	}
	else {
		// Couldn't get hardware, fallback to software.
		dsbuf.dwFlags = DSBCAPS_CTRLFREQUENCY | DSBCAPS_LOCSOFTWARE;
		if (use8) {
			dsbuf.dwFlags |= DSBCAPS_GETCURRENTPOSITION2;
		}
		if (DS_OK != pDS->CreateSoundBuffer(&dsbuf, &pDSBuf, NULL)) {
			Com_Printf( "failed\n" );
			SNDDMA_Shutdown ();
			return qfalse;
		}
		Com_DPrintf( "forced to software.  ok\n" );
	}
		
	// Make sure mixer is active
	if ( DS_OK != pDSBuf->Play(0, 0, DSBPLAY_LOOPING) ) {
		Com_Printf ("*** Looped sound play failed ***\n");
		SNDDMA_Shutdown ();
		return qfalse;
	}

	// get the returned buffer size
	if ( DS_OK != pDSBuf->GetCaps (&dsbcaps) ) {
		Com_Printf ("*** GetCaps failed ***\n");
		SNDDMA_Shutdown ();
		return qfalse;
	}
	
	gSndBufSize = dsbcaps.dwBufferBytes;

	dma.channels = format.nChannels;
	dma.samplebits = format.wBitsPerSample;
	dma.speed = format.nSamplesPerSec;
	dma.samples = gSndBufSize/(dma.samplebits/8);
	dma.submission_chunk = 1;
	dma.buffer = NULL;			// must be locked first

	sample16 = (dma.samplebits/8) - 1;

	SNDDMA_BeginPainting ();
	if (dma.buffer)
		memset(dma.buffer, 0, dma.samples * dma.samplebits/8);
	SNDDMA_Submit ();
	return 1;
}
Exemplo n.º 30
0
internal void InitializeSound(HWND window, int32 bufferSize, int32 samplesPerSecond)
{
	// First load the library
	HMODULE library = LoadLibraryA("dsound.dll");

	if(library)
	{
		// Get a directSound object.
		direct_sound_create *directSoundCreate = (direct_sound_create *)GetProcAddress(library, "DirectSoundCreate");
		LPDIRECTSOUND directSound;
		if(directSoundCreate && SUCCEEDED(directSoundCreate(0, &directSound, 0)))
		{
			WAVEFORMATEX waveformat;
			waveformat.wFormatTag = WAVE_FORMAT_PCM;
			waveformat.nChannels = 2;
			waveformat.nSamplesPerSec = samplesPerSecond;
			waveformat.wBitsPerSample = 16;
			waveformat.nBlockAlign = waveformat.nChannels * waveformat.wBitsPerSample / 8;
			waveformat.nAvgBytesPerSec = waveformat.nSamplesPerSec * waveformat.nBlockAlign;
			waveformat.cbSize = 0;

			if(SUCCEEDED(directSound->SetCooperativeLevel(window, DSSCL_PRIORITY)))
			{

				DSBUFFERDESC bufferDescription = {};
				bufferDescription.dwSize = sizeof(bufferDescription);
				bufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;
				bufferDescription.dwBufferBytes = 0;
				// Responsible for creating a handle to the sound card and configures the sound card using the wave format we defined above.
				// TODO: Is this even necessary now?
				LPDIRECTSOUNDBUFFER primaryBuffer;
				if(SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &primaryBuffer, 0)))
				{
					if(SUCCEEDED(primaryBuffer->SetFormat(&waveformat)))
					{
						OutputDebugStringA("Primary buffer set/n");
					};
				}
			}
			else{
				// TODO: log diagnostic
			}

			DSBUFFERDESC bufferDescription = {};
			bufferDescription.dwSize = sizeof(bufferDescription);
			bufferDescription.dwFlags = 0;
			bufferDescription.dwBufferBytes = bufferSize;
			bufferDescription.lpwfxFormat = &waveformat;


			if(SUCCEEDED(directSound->CreateSoundBuffer(&bufferDescription, &audioBuffer, 0)))
			{
				OutputDebugStringA("Secondary buffer created/n");
			}
		}
		else{
			// TODO: Log direct sound not loaded.
		}
		// Create a primary buffer

		// Create a secondary buffer which is what we will actually write to

		// Start playing
	}
}