void GameAudio::processPunchSound()
{
	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_PUNCH] == true)
	{
		Game *game = Game::getSingleton();
		GameStateManager *gsm = game->getGSM();
		SpriteManager *spriteMgr = gsm->getSpriteManager();
		PlayerSprite *player = spriteMgr->getPlayer();

		wstring playerState = player->getCurrentState();

		if (playerState.compare(L"PUNCH_LEFT") == 0 || playerState.compare(L"PUNCH_RIGHT") == 0
			|| playerState.compare(L"PUNCH_BACK") == 0 || playerState.compare(L"PUNCH_FRONT") == 0)
		{
			IXAudio2SourceVoice *punchSound = soundEffectMap[ENUM_SOUND_EFFECT_PUNCH];

			XAUDIO2_VOICE_STATE voiceState;
			punchSound->GetState(&voiceState);

			//// [voiceState.BuffersQueued <= 0] means there are nothing in the buffer
			//// so let's make a new buffer to queue the sound
			if (voiceState.BuffersQueued <= 0)
			{
				XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_PUNCH];
				bool ssbSuccess = SUCCEEDED(punchSound->SubmitSourceBuffer(proto));
				punchSound->Start();
			}
			//// if there is something in the buffer
			else
			{
				/// do nothing
			}
		}
	}
}
void GameAudio::processHealSound()
{
	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_HEAL] == true)
	{
		Game *game = Game::getSingleton();
		GameStateManager *gsm = game->getGSM();
		SpriteManager *spriteMgr = gsm->getSpriteManager();
		PlayerSprite *player = spriteMgr->getPlayer();

		bool isHealing = player->getIshealing();

		if (isHealing == true)
		{
			IXAudio2SourceVoice *healSound = soundEffectMap[ENUM_SOUND_EFFECT_HEAL];

			XAUDIO2_VOICE_STATE voiceState;
			healSound->GetState(&voiceState);

			//// [voiceState.BuffersQueued <= 0] means there are nothing in the buffer
			//// so let's make a new buffer to queue the sound
			if (voiceState.BuffersQueued <= 0)
			{
				XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_HEAL];
				bool ssbSuccess = SUCCEEDED(healSound->SubmitSourceBuffer(proto));
				healSound->Start();
				//// After all, there will be only one buffer node in the queue always ...
			}
			//// if there is something in the buffer
			else
			{
				/// do nothing
			}
		}
	}
}
Example #3
0
	virtual const char* write_frame( void * buffer, unsigned num_samples, bool wait )
	{
		if ( paused )
		{
			if ( wait ) Sleep( MulDiv( num_samples / nch, 1000, sample_rate ) );
			return 0;
		}

		if ( reopen_count )
		{
			if ( ! --reopen_count )
			{
				const char * err = open( hwnd, sample_rate, nch, max_samples_per_frame, num_frames );
				if ( err )
				{
					reopen_count = 60 * 5;
					return err;
				}
			}
			else
			{
				if ( wait ) Sleep( MulDiv( num_samples / nch, 1000, sample_rate ) );
				return 0;
			}
		}

		for (;;) {
			sVoice->GetState( &vState );
			assert( vState.BuffersQueued <= num_frames );
			if( vState.BuffersQueued < num_frames ) {
				if( vState.BuffersQueued == 0 ) {
					// buffers ran dry
				}
				// there is at least one free buffer
				break;
			} else {
				// wait for one buffer to finish playing
				ResetEvent( notify.hBufferEndEvent );
				WaitForSingleObject( notify.hBufferEndEvent, INFINITE );
			}
		}
		samples_in_buffer[ buffer_write_cursor ] = num_samples / nch;
		XAUDIO2_BUFFER buf = {0};
		unsigned num_bytes = num_samples * 2;
		buf.AudioBytes = num_bytes;
		buf.pAudioData = ( const BYTE * )( sample_buffer + max_samples_per_frame * buffer_write_cursor );
		buf.pContext = this;
		buffer_write_cursor = ( buffer_write_cursor + 1 ) % num_frames;
		memcpy( ( void * ) buf.pAudioData, buffer, num_bytes );
		if( sVoice->SubmitSourceBuffer( &buf ) == S_OK )
		{
			InterlockedIncrement( &buffered_count );
			return 0;
		}

		close();
		reopen_count = 60 * 5;

		return 0;
	}
Example #4
0
static void
XAUDIO2_CloseDevice(_THIS)
{
    if (_this->hidden != NULL) {
        IXAudio2 *ixa2 = _this->hidden->ixa2;
        IXAudio2SourceVoice *source = _this->hidden->source;
        IXAudio2MasteringVoice *mastering = _this->hidden->mastering;

        if (source != NULL) {
			source->Stop();
            source->FlushSourceBuffers();
            source->DestroyVoice();
        }
        if (ixa2 != NULL) {
            ixa2->StopEngine();
        }
        if (mastering != NULL) {
            mastering->DestroyVoice();
        }
        if (ixa2 != NULL) {
            ixa2->Release();
        }
        SDL_free(_this->hidden->mixbuf);
        if (_this->hidden->semaphore != NULL) {
            CloseHandle(_this->hidden->semaphore);
        }

        SDL_free(_this->hidden);
        _this->hidden = NULL;
    }
}
Example #5
0
void XAudio2_Output::close()
{
	initialized = false;

	if( sVoice ) {
		if( playing ) {
			HRESULT hr = sVoice->Stop( 0 );
			ASSERT( hr == S_OK );
		}
		sVoice->DestroyVoice();
		sVoice = NULL;
	}

	if( buffers ) {
		free( buffers );
		buffers = NULL;
	}

	if( mVoice ) {
		mVoice->DestroyVoice();
		mVoice = NULL;
	}

	if( xaud ) {
		xaud->Release();
		xaud = NULL;
	}
}
Example #6
0
	virtual const char* pause( bool pausing )
	{
		if ( pausing )
		{
			if ( ! paused )
			{
				paused = true;
				HRESULT hr = sVoice->Stop( 0 );
				if ( FAILED(hr) )
				{
					close();
					reopen_count = 60 * 5;
				}
			}
		}
		else
		{
			if ( paused )
			{
				paused = false;
				HRESULT hr = sVoice->Start( 0 );
				if ( FAILED(hr) )
				{
					close();
					reopen_count = 60 * 5;
				}
			}
		}

		return 0;
	}
void GameAudio::stopMusic(MusicTypes musicType)
{
	if (musicRegistrationMap[musicType] == true)
	{
		IXAudio2SourceVoice *sourceVoice = musicMap[musicType];
		sourceVoice->Stop();
		sourceVoice->FlushSourceBuffers();
	}
}
Example #8
0
	bool Audio::AddAudioFile(const char* i_AudioPath, bool bLoop, float i_InitialVolume)
	{
		WAVEFORMATEXTENSIBLE wfx = { 0 };
		XAUDIO2_BUFFER buffer = { 0 };

		// Open the file
		HANDLE hFile = CreateFile(
			i_AudioPath,
			GENERIC_READ,
			FILE_SHARE_READ,
			NULL,
			OPEN_EXISTING,
			0,
			NULL);


		SetFilePointer(hFile, 0, NULL, FILE_BEGIN);

		DWORD dwChunkSize;
		DWORD dwChunkPosition;
		//check the file type, should be fourccWAVE or 'XWMA'
		FindChunk(hFile, fourccRIFF, dwChunkSize, dwChunkPosition);
		DWORD filetype;
		ReadChunkData(hFile, &filetype, sizeof(DWORD), dwChunkPosition);
		if (filetype != fourccWAVE)
			return false;

		FindChunk(hFile, fourccFMT, dwChunkSize, dwChunkPosition);
		ReadChunkData(hFile, &wfx, dwChunkSize, dwChunkPosition);

		//fill out the audio data buffer with the contents of the fourccDATA chunk
		FindChunk(hFile, fourccDATA, dwChunkSize, dwChunkPosition);
		BYTE * pDataBuffer = new BYTE[dwChunkSize];
		ReadChunkData(hFile, pDataBuffer, dwChunkSize, dwChunkPosition);

		buffer.AudioBytes = dwChunkSize;  //buffer containing audio data
		buffer.pAudioData = pDataBuffer;  //size of the audio buffer in bytes
		buffer.Flags = XAUDIO2_END_OF_STREAM; // tell the source voice not to expect any data after this buffer
		if (bLoop)
		{
			buffer.LoopLength = 0;
			buffer.LoopCount = XAUDIO2_LOOP_INFINITE;
		}

		HRESULT hr;
		IXAudio2SourceVoice* pSourceVoice;
		if (FAILED(hr = s_pXAudio2->CreateSourceVoice(&pSourceVoice, (WAVEFORMATEX*)&wfx)))
			return false;

		if (FAILED(hr = pSourceVoice->SubmitSourceBuffer(&buffer)))
			return false;

		pSourceVoice->SetVolume(i_InitialVolume);

		s_SourceVoices.push_back(pSourceVoice);
		s_AudioBuffers.push_back(buffer);
	}
Example #9
0
	virtual const char* open( void * hwnd, unsigned sample_rate, unsigned nch, unsigned max_samples_per_frame, unsigned num_frames )
	{
		this->hwnd = hwnd;
		this->sample_rate = sample_rate;
		this->nch = nch;
		this->max_samples_per_frame = max_samples_per_frame;
		this->num_frames = num_frames;

#ifdef HAVE_KS_HEADERS
		WAVEFORMATEXTENSIBLE wfx;
		wfx.Format.wFormatTag = WAVE_FORMAT_EXTENSIBLE;
		wfx.Format.nChannels = nch; //1;
		wfx.Format.nSamplesPerSec = sample_rate;
		wfx.Format.nBlockAlign = 2 * nch; //2;
		wfx.Format.nAvgBytesPerSec = wfx.Format.nSamplesPerSec * wfx.Format.nBlockAlign;
		wfx.Format.wBitsPerSample = 16;
		wfx.Format.cbSize = sizeof(WAVEFORMATEXTENSIBLE)-sizeof(WAVEFORMATEX);
		wfx.Samples.wValidBitsPerSample = 16;
		wfx.SubFormat = KSDATAFORMAT_SUBTYPE_PCM;
		wfx.dwChannelMask = nch == 2 ? KSAUDIO_SPEAKER_STEREO : KSAUDIO_SPEAKER_MONO;
#else
		WAVEFORMATEX wfx;
		wfx.wFormatTag = WAVE_FORMAT_PCM;
		wfx.nChannels = nch; //1;
		wfx.nSamplesPerSec = sample_rate;
		wfx.nBlockAlign = 2 * nch; //2;
		wfx.nAvgBytesPerSec = wfx.nSamplesPerSec * wfx.nBlockAlign;
		wfx.wBitsPerSample = 16;
		wfx.cbSize = 0;
#endif
        HRESULT hr = XAudio2Create( &xaud, 0 );
		if (FAILED(hr)) return "Creating XAudio2 interface";
		hr = xaud->CreateMasteringVoice(
			&mVoice,
			nch,
			sample_rate,
			0,
			NULL,
			NULL );
		if (FAILED(hr)) return "Creating XAudio2 mastering voice";
		hr = xaud->CreateSourceVoice( &sVoice, &wfx, 0, 4.0f, &notify );
		if (FAILED(hr)) return "Creating XAudio2 source voice";
		hr = sVoice->Start( 0 );
		if (FAILED(hr)) return "Starting XAudio2 voice";
		hr = sVoice->SetFrequencyRatio((float)1.0f);
		if (FAILED(hr)) return "Setting XAudio2 voice frequency ratio";
		buffered_count = 0;
		buffer_read_cursor = 0;
		buffer_write_cursor = 0;
		samples_played = 0;
		sample_buffer = new int16_t[ max_samples_per_frame * num_frames ];
		samples_in_buffer = new UINT64[ num_frames ];
		memset( samples_in_buffer, 0, sizeof( UINT64 ) * num_frames );
		return NULL;
	}
Example #10
0
static void
XAUDIO2_WaitDone(_THIS)
{
    IXAudio2SourceVoice *source = _this->hidden->source;
    XAUDIO2_VOICE_STATE state;
    SDL_assert(!_this->enabled);  /* flag that stops playing. */
    source->Discontinuity();
    source->GetState(&state);
    while (state.BuffersQueued > 0) {
        WaitForSingleObjectEx(_this->hidden->semaphore, INFINITE, 0);
        source->GetState(&state);
    }
}
Example #11
0
void XAudio2_Output::reset()
{
	if( !initialized || failed ) return;

	if( playing ) {
		HRESULT hr = sVoice->Stop( 0 );
		ASSERT( hr == S_OK );
	}

	sVoice->FlushSourceBuffers();
	sVoice->Start( 0 );
	playing = true;
}
Example #12
0
void XAudio2_Output::write(u16 * finalWave, int length)
{
	if( !initialized || failed ) return;

	while( true ) {
		if ( device_changed ) {
			close();
			if (!init(freq)) return;
		}

		sVoice->GetState( &vState );

		ASSERT( vState.BuffersQueued <= bufferCount );

		if( vState.BuffersQueued < bufferCount ) {
			if( vState.BuffersQueued == 0 ) {
				// buffers ran dry
				if( systemVerbose & VERBOSE_SOUNDOUTPUT ) {
					static unsigned int i = 0;
					log( "XAudio2: Buffers were not refilled fast enough (i=%i)\n", i++ );
				}
			}
			// there is at least one free buffer
			break;
		} else {
			// the maximum number of buffers is currently queued
			if( synchronize && !speedup && !theApp.throttle ) {
				// wait for one buffer to finish playing
				if (WaitForSingleObject( notify.hBufferEndEvent, 10000 ) == WAIT_TIMEOUT) {
					device_changed = true;
				}
			} else {
				// drop current audio frame
				return;
			}
		}
	}

	// copy & protect the audio data in own memory area while playing it
	CopyMemory( &buffers[ currentBuffer * soundBufferLen ], finalWave, soundBufferLen );

	buf.AudioBytes = soundBufferLen;
	buf.pAudioData = &buffers[ currentBuffer * soundBufferLen ];

	currentBuffer++;
	currentBuffer %= ( bufferCount + 1 ); // + 1 because we need one temporary buffer

	HRESULT hr = sVoice->SubmitSourceBuffer( &buf ); // send buffer to queue
	ASSERT( hr == S_OK );
}
void SoundManager::update(Camera* p_gameCamera)
{
	m_masterVoice->SetVolume(m_masterVolume,0);
	updateListener(p_gameCamera);

	X3DAudioCalculate(m_X3DAudioInstance, &m_listener, &m_music->getEmitter(),
		X3DAUDIO_CALCULATE_MATRIX, &m_music->getDSPSettings());

	IXAudio2SourceVoice* voice = m_music->getSource();
	m_left = m_matrixCoefficients[0];
	m_right = m_matrixCoefficients[1];
	voice->SetOutputMatrix( m_masterVoice, 1, m_destChannels, m_matrixCoefficients);

	if(!m_music->isPlaying())
		m_music->play();
}
Example #14
0
void XAudio2_Output::setThrottle( unsigned short throttle )
{
	if( !initialized || failed ) return;

	if( throttle == 0 ) throttle = 100;
	HRESULT hr = sVoice->SetFrequencyRatio( (float)throttle / 100.0f );
	ASSERT( hr == S_OK );
}
void GameAudio::playMusicRepeat(MusicTypes musicType)
{
	if (musicRegistrationMap[musicType] == true)
	{
		IXAudio2SourceVoice *sourceVoice = musicMap[musicType];

		XAUDIO2_VOICE_STATE voiceState;
		sourceVoice->GetState(&voiceState);

		if (voiceState.BuffersQueued <= 0)
		{
			XAUDIO2_BUFFER *proto = musicBufferPrototypeMap[musicType];
			bool ssbSuccess = SUCCEEDED(sourceVoice->SubmitSourceBuffer(proto));
			sourceVoice->Start();
		}
	}
}
Example #16
0
	virtual double buffered()
	{
		sVoice->GetState( &vState );
		double buffered_count = vState.BuffersQueued;
		INT64 samples_played = vState.SamplesPlayed - this->samples_played;
		buffered_count -= double( samples_played ) / double( max_samples_per_frame / nch );
		return buffered_count;
	}
Example #17
0
void StreamingVoiceContext2_7::SubmitBuffer(PBYTE buf_data)
{
	XAUDIO2_BUFFER buf = {};
	buf.AudioBytes = BUFFER_SIZE_BYTES;
	buf.pContext = buf_data;
	buf.pAudioData = buf_data;

	m_source_voice->SubmitSourceBuffer(&buf);
}
Example #18
0
void XAudio2_Output::pause()
{
	if( !initialized || failed ) return;

	if( playing ) {
		HRESULT hr = sVoice->Stop( 0 );
		ASSERT( hr == S_OK );
		playing = false;
	}
}
Example #19
0
void XAudio2_Output::resume()
{
	if( !initialized || failed ) return;

	if( !playing ) {
		HRESULT hr = sVoice->Start( 0 );
		ASSERT( hr == S_OK );
		playing = true;
	}
}
void GameAudio::processMoneySound()
{
	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_MONEY] == true)
	{
		if (moneySoundSignal == true)
		{
			IXAudio2SourceVoice *moneySound = soundEffectMap[ENUM_SOUND_EFFECT_MONEY];

			XAUDIO2_VOICE_STATE voiceState;
			moneySound->GetState(&voiceState);

			XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_MONEY];
			bool ssbSuccess = SUCCEEDED(moneySound->SubmitSourceBuffer(proto));
			moneySound->Start();

			moneySoundSignal = false;
		}
	}
}
void GameAudio::playMusicOnce(MusicTypes musicType)
{
	if (musicRegistrationMap[musicType] == true)
	{
		IXAudio2SourceVoice *sourceVoice = musicMap[musicType];

		XAUDIO2_VOICE_STATE voiceState;
		sourceVoice->GetState(&voiceState);

		if (musicType == ENUM_MUSIC_LEVEL_COMPLETE)
		{
			if (levelCompleteMusicBuffered == false)
			{
				XAUDIO2_BUFFER *proto = musicBufferPrototypeMap[musicType];
				bool ssbSuccess = SUCCEEDED(sourceVoice->SubmitSourceBuffer(proto));
				sourceVoice->Start();
				levelCompleteMusicBuffered = true;
			}
		}

		/// here put the game over music
		else if (musicType == ENUM_MUSIC_GAMEOVER)
		{
			if (gameOverMusicBuffered == false)
			{
				XAUDIO2_BUFFER *proto = musicBufferPrototypeMap[musicType];
				bool ssbSuccess = SUCCEEDED(sourceVoice->SubmitSourceBuffer(proto));
				sourceVoice->Start();
				gameOverMusicBuffered = true;
			}
		}
	}
}
Example #22
0
static void
XAUDIO2_PlayDevice(_THIS)
{
    XAUDIO2_BUFFER buffer;
    Uint8 *mixbuf = _this->hidden->mixbuf;
    Uint8 *nextbuf = _this->hidden->nextbuf;
    const int mixlen = _this->hidden->mixlen;
    IXAudio2SourceVoice *source = _this->hidden->source;
    HRESULT result = S_OK;

    if (!_this->enabled) { /* shutting down? */
        return;
    }

    /* Submit the next filled buffer */
    SDL_zero(buffer);
    buffer.AudioBytes = mixlen;
    buffer.pAudioData = nextbuf;
    buffer.pContext = _this;
	buffer.LoopCount = 1;

    if (nextbuf == mixbuf) {
        nextbuf += mixlen;
    } else {
        nextbuf = mixbuf;
    }
    _this->hidden->nextbuf = nextbuf;

    result = source->SubmitSourceBuffer(&buffer);
    if (result == XAUDIO2_E_DEVICE_INVALIDATED) {
        /* !!! FIXME: possibly disconnected or temporary lost. Recover? */
    }

    if (result != S_OK) {  /* uhoh, panic! */
         source->FlushSourceBuffers();
         _this->enabled = 0;
    }
}
Example #23
0
void XAudio2Streamer::Stream( void const *pSamples )
{
    // Verify buffer availability
    XAUDIO2_VOICE_STATE xa2vs;
    m_pXAudio2SourceVoice->GetState( &xa2vs );
    if( xa2vs.BuffersQueued == m_count )
        return;

    // Copy samples to buffer
    Sample *pBuffer( &m_samples[ m_index * m_size ] );
    using std::memcpy;
    memcpy( pBuffer, pSamples, m_size );

    // Submit buffer to voice
    XAUDIO2_BUFFER xa2b = {};
    xa2b.AudioBytes = UINT32( m_size );
    xa2b.pAudioData = pBuffer;
    if( FAILED( m_pXAudio2SourceVoice->SubmitSourceBuffer( &xa2b ) ) )
        return;

    // Select next buffer
    m_index = ( m_index + 1 ) % m_count;
}
Example #24
0
	void close()
	{
		if( sVoice ) {
			if( !paused ) {
				sVoice->Stop( 0 );
			}
			sVoice->DestroyVoice();
		}

		if( mVoice ) {
			mVoice->DestroyVoice();
		}

		if( xaud ) {
			xaud->Release();
			xaud = NULL;
		}

		delete [] sample_buffer;
		sample_buffer = NULL;
		delete [] samples_in_buffer;
		samples_in_buffer = NULL;
	}
Example #25
0
void WMA::Play()
{
    HRESULT hr;

    //uint32_t decodedDataSize = GetSize();
    /*uint32_t decodedDataSize = m_WaveFormatEx.nSamplesPerSec * m_WaveFormatEx.wBitsPerSample / 8 * m_WaveFormatEx.nChannels * 6;

    uint32_t readSize = 0;

    BYTE * data1 = new BYTE[decodedDataSize];
    SingleRead( data1, decodedDataSize, &readSize );
    XAUDIO2_BUFFER buffer1 = {0};
    buffer1.AudioBytes = readSize;
    buffer1.Flags = XAUDIO2_END_OF_STREAM;
    buffer1.pAudioData = data1;*/

    mMaxBufferSize = 0;
    hr = m_pReaderAdvanced->GetMaxOutputSampleSize( 0, &mMaxBufferSize );

    //mMaxBufferSize = m_WaveFormatEx.nSamplesPerSec * m_WaveFormatEx.wBitsPerSample / 8 * m_WaveFormatEx.nChannels * 2;

    if( FAILED( hr = gXAudio->CreateSourceVoice( &mSourceVoice, &m_WaveFormatEx, 0, XAUDIO2_DEFAULT_FREQ_RATIO, &mVoiceCallback, NULL, NULL ) ))
    {
        std::cout << "Error creating source buffer:" << hr << std::endl;
        return;
    }

    if( FAILED( hr = mSourceVoice->Start( 0, XAUDIO2_COMMIT_NOW ) ) ) {
        std::cout << "Error starting buffer" << std::endl;
        return;
    }

    //mDecodedBuffers = new uint8_t[MAX_BUFFER_COUNT * (mMaxBufferSize + DECODING_BUFFER_ERROR)];
    mDecodedBuffers = new uint8_t[MAX_BUFFER_COUNT * mMaxBufferSize];
    mCurrentBuffer = 0;
    mCurrentTime = 0;

    hr = m_pReader->Start(0, 0, 1.0f, this);
    if( FAILED(hr) ) {
        std::cout << "Error starting decoder" << std::endl;
        return;
    }

    /*if( FAILED( hr = mSourceVoice->SubmitSourceBuffer( &buffer1 ) ) ) {
    	std::cout << "Error submitting source buffer:" << hr << std::endl;
    	return;
    }*/
}
Example #26
0
	HRESULT SubmitBuffer()
	{
		// Ensure we do have a valid voice
		if (this->SourceVoice == nullptr)
		{
			return E_FAIL;
		}

		MxMixSamples(this->buffer, this->bufferLength / 4);

		XAUDIO2_BUFFER buf = { 0 };
		buf.AudioBytes = this->bufferLength;
		buf.pAudioData = (const BYTE *) this->buffer;

		return SourceVoice->SubmitSourceBuffer(&buf);
	}
Example #27
0
/* Loads a sound with the specified id and path
 */
void XAudioSoundSystem::OnLoadSound(uint32 soundID, const char* szSoundPath)
{
	if(mSounds[soundID] != NULL)
		return;

	HRESULT hr = S_OK;

	char szFullPath[1024];
	sprintf_s(szFullPath, 1024, "Data/Win32/%s", szSoundPath);
		
    size_t convertedChars = 0;
    wchar_t wpath[1024];
	mbstowcs_s(&convertedChars, wpath, strlen(szFullPath) + 1, szFullPath, _TRUNCATE);

    //
    // Read in the wave file
    //
    CWaveFile wav;
    if( FAILED( hr = wav.Open( wpath, NULL, WAVEFILE_READ ) ) )
    {
        wprintf( L"Failed reading WAV file: %#X (%s)\n", hr, wpath );
        return;
    }

    // Get format of wave file
    WAVEFORMATEX* pwfx = wav.GetFormat();

    // Calculate how many bytes and samples are in the wave
    DWORD cbWaveSize = wav.GetSize();

    // Read the sample data into memory
    BYTE* pbWaveData = new BYTE[ cbWaveSize ];

    if( FAILED( hr = wav.Read( pbWaveData, cbWaveSize, &cbWaveSize ) ) )
    {
        wprintf( L"Failed to read WAV data: %#X\n", hr );
        SAFE_DELETE_ARRAY( pbWaveData );
        return;
    }

    //
    // Play the wave using a XAudio2SourceVoice
    //

    // Create the source voice
    IXAudio2SourceVoice* pSourceVoice;
    if( FAILED( hr = mXAudio2->CreateSourceVoice( &pSourceVoice, pwfx ) ) )
    {
        wprintf( L"Error %#X creating source voice\n", hr );
        SAFE_DELETE_ARRAY( pbWaveData );
        return;
    }

    // Submit the wave sample data using an XAUDIO2_BUFFER structure
    XAUDIO2_BUFFER buffer = {0};
    buffer.pAudioData = pbWaveData;
    buffer.Flags = XAUDIO2_END_OF_STREAM;  // tell the source voice not to expect any data after this buffer
    buffer.AudioBytes = cbWaveSize;

    if( FAILED( hr = pSourceVoice->SubmitSourceBuffer( &buffer ) ) )
    {
        wprintf( L"Error %#X submitting source buffer\n", hr );
        pSourceVoice->DestroyVoice();
        SAFE_DELETE_ARRAY( pbWaveData );
        return;
    }

	Sound* pSound = new Sound();
	pSound->mVoice = pSourceVoice;
	pSound->mAudioBuffer = buffer;
	pSound->mData = pbWaveData;
	pSound->mStarted = false;

	mSounds[soundID] = pSound;
}	
Example #28
0
void WaveBank::Impl::Play( int index )
{
    if ( mStreaming )
    {
        DebugTrace( "ERROR: One-shots can only be created from an in-memory wave bank\n");
        throw std::exception( "WaveBank::Play" );
    }

    if ( index < 0 || uint32_t(index) >= mReader.Count() )
    {
        DebugTrace( "WARNING: Index %d not found in wave bank with only %u entries, one-shot not triggered\n", index, mReader.Count() );
        return;
    }

    if ( !mPrepared )
    {
        mReader.WaitOnPrepare();
        mPrepared = true;
    }

    char wfxbuff[64];
    auto wfx = reinterpret_cast<WAVEFORMATEX*>( wfxbuff );
    HRESULT hr = mReader.GetFormat( index, wfx, 64 );
    ThrowIfFailed( hr );

    IXAudio2SourceVoice* voice = nullptr;
    mEngine->AllocateVoice( wfx, SoundEffectInstance_Default, true, &voice );

    if ( !voice )
        return;

    hr = voice->Start( 0 );
    ThrowIfFailed( hr );

    XAUDIO2_BUFFER buffer;
    memset( &buffer, 0, sizeof(buffer) );

    hr = mReader.GetWaveData( index, &buffer.pAudioData, buffer.AudioBytes );
    ThrowIfFailed( hr );

    WaveBankReader::Metadata metadata;
    hr = mReader.GetMetadata( index, metadata );
    ThrowIfFailed( hr );

    buffer.Flags = XAUDIO2_END_OF_STREAM;
    buffer.pContext = this;

#if defined(_XBOX_ONE) || (_WIN32_WINNT < _WIN32_WINNT_WIN8)

    XAUDIO2_BUFFER_WMA wmaBuffer;
    memset( &wmaBuffer, 0, sizeof(wmaBuffer) );

    uint32_t tag;
    hr = mReader.GetSeekTable( index, &wmaBuffer.pDecodedPacketCumulativeBytes, wmaBuffer.PacketCount, tag );
    ThrowIfFailed( hr );

    if ( tag == WAVE_FORMAT_WMAUDIO2 || tag == WAVE_FORMAT_WMAUDIO3 )
    {
        hr = voice->SubmitSourceBuffer( &buffer, &wmaBuffer );
    }
    else
#endif
    {
        hr = voice->SubmitSourceBuffer( &buffer, nullptr );
    }
    if ( FAILED(hr) )
    {
        DebugTrace( "ERROR: WaveBank failed (%08X) when submitting buffer:\n", hr );
        DebugTrace( "\tFormat Tag %u, %u channels, %u-bit, %u Hz, %u bytes\n", wfx->wFormatTag, 
                    wfx->nChannels, wfx->wBitsPerSample, wfx->nSamplesPerSec, metadata.lengthBytes );
        throw std::exception( "SubmitSourceBuffer" );
    }

    InterlockedIncrement( &mOneShots );
}
void GameAudio::shutDown()
{
	//// ---- destroy sound effects
	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_SHOOT] == true)
	{
		IXAudio2SourceVoice* shootSound = soundEffectMap[ENUM_SOUND_EFFECT_SHOOT];
		shootSound->DestroyVoice();

		XAUDIO2_BUFFER *buffer = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_SHOOT];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_MONEY] == true)
	{
		IXAudio2SourceVoice* moneySound = soundEffectMap[ENUM_SOUND_EFFECT_MONEY];
		moneySound->DestroyVoice();

		XAUDIO2_BUFFER *buffer = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_MONEY];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_PUNCH] == true)
	{
		IXAudio2SourceVoice* punchSound = soundEffectMap[ENUM_SOUND_EFFECT_PUNCH];
		punchSound->DestroyVoice();

		XAUDIO2_BUFFER *buffer = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_PUNCH];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_HEAL] == true)
	{
		IXAudio2SourceVoice* healSound = soundEffectMap[ENUM_SOUND_EFFECT_HEAL];
		healSound->DestroyVoice();

		XAUDIO2_BUFFER *buffer = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_HEAL];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_DAMAGE] == true)
	{
		IXAudio2SourceVoice* damageSound = soundEffectMap[ENUM_SOUND_EFFECT_DAMAGE];
		damageSound->DestroyVoice();

		XAUDIO2_BUFFER *buffer = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_DAMAGE];
		delete[] buffer->pAudioData;
		delete buffer;
	}
	//// --- destory sound effects complete

	//// --- destroy musics
	if (musicRegistrationMap[ENUM_MUSIC_MAIN_THEME] == true)
	{
		IXAudio2SourceVoice* mainTheme = musicMap[ENUM_MUSIC_MAIN_THEME];
		mainTheme->DestroyVoice();

		XAUDIO2_BUFFER *buffer = musicBufferPrototypeMap[ENUM_MUSIC_MAIN_THEME];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (musicRegistrationMap[ENUM_MUSIC_LEVEL_COMPLETE] == true)
	{
		IXAudio2SourceVoice* completeMusic = musicMap[ENUM_MUSIC_LEVEL_COMPLETE];
		completeMusic->DestroyVoice();

		XAUDIO2_BUFFER *buffer = musicBufferPrototypeMap[ENUM_MUSIC_LEVEL_COMPLETE];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (musicRegistrationMap[ENUM_MUSIC_INGAME] == true)
	{
		IXAudio2SourceVoice* ingameMusic = musicMap[ENUM_MUSIC_INGAME];
		ingameMusic->DestroyVoice();

		XAUDIO2_BUFFER *buffer = musicBufferPrototypeMap[ENUM_MUSIC_INGAME];
		delete[] buffer->pAudioData;
		delete buffer;
	}

	if (musicRegistrationMap[ENUM_MUSIC_GAMEOVER] == true)
	{
		IXAudio2SourceVoice* gameoverMusic = musicMap[ENUM_MUSIC_GAMEOVER];
		gameoverMusic->DestroyVoice();

		XAUDIO2_BUFFER *buffer = musicBufferPrototypeMap[ENUM_MUSIC_GAMEOVER];
		delete[] buffer->pAudioData;
		delete buffer;
	}
	//// --- destroy musics complete


	//// --- put other effects' destructors here ------

	masterVoice->DestroyVoice();
	xAudio2Engine->Release();
	CoUninitialize();
}
void GameAudio::processShootSound()
{
	if (soundEffectRegistrationMap[ENUM_SOUND_EFFECT_SHOOT] == true)
	{
		Game *game = Game::getSingleton();
		GameStateManager *gsm = game->getGSM();
		SpriteManager *spriteMgr = gsm->getSpriteManager();
		/*if (moneySoundSignal == true)
		{
			IXAudio2SourceVoice *moneySound = soundEffectMap[ENUM_SOUND_EFFECT_MONEY];

			XAUDIO2_VOICE_STATE voiceState;
			moneySound->GetState(&voiceState);

			XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_MONEY];
			bool ssbSuccess = SUCCEEDED(moneySound->SubmitSourceBuffer(proto));
			moneySound->Start();

			moneySoundSignal = false;
		}
		*/
		if (shootSoundSignal == true)
		{
			IXAudio2SourceVoice *shootSound = soundEffectMap[ENUM_SOUND_EFFECT_SHOOT];

			XAUDIO2_VOICE_STATE voiceState;
			shootSound->GetState(&voiceState);

			XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_SHOOT];
			bool ssbSuccess = SUCCEEDED(shootSound->SubmitSourceBuffer(proto));
			shootSound->Start();

			shootSoundSignal = false;
		}

		/*
		list<Bot*>::iterator botIt = spriteMgr->getBotsIterator();
		list<Bot*>::iterator endBotIt = spriteMgr->getEndOfBotsIterator();
		while (botIt != endBotIt)
		{
		Bot *bot = (*botIt);
		wstring botCurState = bot->getCurrentState();
		if (botCurState.compare(L"SHOOT_LEFT") == 0 || botCurState.compare(L"SHOOT_RIGHT") == 0
		|| botCurState.compare(L"SHOOT_BACK") == 0 || botCurState.compare(L"SHOOT_FRONT") == 0)
		{
		IXAudio2SourceVoice *shootSound = soundEffectMap[ENUM_SOUND_EFFECT_SHOOT];

		XAUDIO2_VOICE_STATE voiceState;
		shootSound->GetState(&voiceState);

		if (voiceState.BuffersQueued <= 0)
		{
		XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_SHOOT];
		bool ssbSuccess = SUCCEEDED(shootSound->SubmitSourceBuffer(proto));
		shootSound->Start();
		}
		}
		botIt++;
		}

		PlayerSprite *player = spriteMgr->getPlayer();
		wstring playerState = player->getCurrentState();
		if (playerState.compare(L"SHOOT_LEFT") == 0 || playerState.compare(L"SHOOT_RIGHT") == 0
		|| playerState.compare(L"SHOOT_BACK") == 0 || playerState.compare(L"SHOOT_FRONT") == 0)
		{
		IXAudio2SourceVoice *shootSound = soundEffectMap[ENUM_SOUND_EFFECT_SHOOT];

		XAUDIO2_VOICE_STATE voiceState;
		shootSound->GetState(&voiceState);

		//// [voiceState.BuffersQueued <= 0] means there are nothing in the buffer
		//// so let's make a new buffer to queue the sound
		if (voiceState.BuffersQueued <= 0)
		{
		XAUDIO2_BUFFER *proto = audioBufferPrototypeMap[ENUM_SOUND_EFFECT_SHOOT];
		bool ssbSuccess = SUCCEEDED(shootSound->SubmitSourceBuffer(proto));
		shootSound->Start();
		}
		//// if there is something in the buffer
		else
		{
		/// do nothing
		}
		}
		*/
		
	}
}