ISimpleAudioVolume G/SetMute not updating - c++

Solution: I reference the pointer of a variable instead of the variable itself. Thank you #RomanR.
I'm trying to use GetMute/SetMute through ISimpleAudioVolume, and I'm having trouble with what I'm seeing. When I run GetMute I can see that it's not muted (which is good), but when I mute my audio output, or run SetMute(false) it fails to update anything. I'm not sure if I'm setting up AudioClient correctly, but don't know how to check it.
Thanks!
Edit: I think my issue is somewhere near the top of the initialization chain. When I run check the volume it says it's 100% which isn't true. When I check the device IDs & states, the beginning of the two IDs are a bunch of 0s, and the state says they're both inactive. If I check the AudioSessionControl, there's no name, but it says the session is also inactive.
My guess is that it's somewhere in this stack of init():
check(CoInitialize(NULL));
check(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&m_deviceEnumerator));
check(m_deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_device));
MainVolumeControl.h
#pragma once
#include <cstdio>
#include <windows.h>
#include <audioclient.h>
#include <audiopolicy.h>
#include <Mmdeviceapi.h>
class MainVolumeControl
{
public:
MainVolumeControl();
void init();
void destroy();
void toggleMute();
void GetMute(BOOL* o_mute);
IMMDeviceEnumerator* m_deviceEnumerator;
IMMDevice* m_device;
IAudioClient* m_audioClient;
ISimpleAudioVolume* m_audioVolume;
WAVEFORMATEX* m_pwfx;
};
MainVolumeControl.cpp
MainVolumeControl::MainVolumeControl()
{
m_deviceEnumerator = nullptr;
m_device = nullptr;
m_audioClient = nullptr;
m_audioVolume = nullptr;
m_pwfx = nullptr;
}
void MainVolumeControl::init()
{
// Get Device
check(CoInitialize(NULL));
check(CoCreateInstance(__uuidof(MMDeviceEnumerator), nullptr, CLSCTX_INPROC_SERVER, __uuidof(IMMDeviceEnumerator), (LPVOID*)&m_deviceEnumerator));
check(m_deviceEnumerator->GetDefaultAudioEndpoint(eRender, eConsole, &m_device));
// Get Audio Client
m_device->Activate(__uuidof(IAudioClient), CLSCTX_ALL, NULL, (void**)&m_audioClient);
// Activate Audio Client & Get Service
check(m_audioClient->GetMixFormat(&m_pwfx));
check(m_audioClient->Initialize(AUDCLNT_SHAREMODE_SHARED, 0, 10000000, 0, m_pwfx, NULL));
check(m_audioClient->GetService(__uuidof(ISimpleAudioVolume), (void**)&m_audioVolume));
}
void MainVolumeControl::destroy()
{
// Release the resources
m_audioVolume->Release();
m_audioClient->Release();
m_device->Release();
m_deviceEnumerator->Release();
CoUninitialize();
}
void MainVolumeControl::toggleMute()
{
BOOL mute = 0;
// Getting the mute value
check(m_audioVolume->GetMute(&mute));
check(m_audioVolume->SetMute(!&mute, NULL));
}
void MainVolumeControl::GetMute(BOOL* o_mute)
{
// Finally getting the mute value
check(m_audioVolume->GetMute(o_mute));
}
Main.cpp
int main(int argc, CHAR* argv[])
{
MainVolumeControl mvc;
BOOL mute = 1;
mvc.init();
mvc.GetMute(&mute);
printf("Mute state: %d\n", mute);
printf("Toggling mute\n");
mvc.toggleMute();
mvc.GetMute(&mute);
printf("Mute state: %d\n", mute);
mvc.destroy();
return 0;
}
Output
Mute state: 0
Toggling mute
Mute state: 0

I reference the pointer of a variable instead of the variable itself. Thank you #RomanR.
Should be:
void MainVolumeControl::toggleMute()
{
BOOL mute = 0;
// Getting the mute value
check(m_audioVolume->GetMute(&mute));
check(m_audioVolume->SetMute(!mute, NULL));
}

Related

Changing the title of uwp process

I want to change the title bar of calc.exe. I read that it's done via SetWindowTextA() but when I used this it only change the title of the preview (1) and I want to change title at (2) as well.
Can anyone explain for me why it change the title at (1) not (2) and how can I change the title at (2)
The Calculator title is Text Control Type retrieved using UI Automation. However according to Text Control Type, the IValueProvider is never supported by text controls. So you can’t.
Edit:
#include <Windows.h>
#include <UIAutomation.h>
#include <wchar.h>
int Element(IUIAutomation* automation)
{
// Get the element under the cursor
// Use GetPhysicalCursorPos to interact properly with
// High DPI
POINT pt;
GetPhysicalCursorPos(&pt);
IUIAutomationElement* pAtMouse;
HRESULT hr = automation->ElementFromPoint(pt, &pAtMouse);
if (FAILED(hr))
return hr;
// Get the element's name and print it
BSTR name;
hr = pAtMouse->get_CurrentName(&name);
if (SUCCEEDED(hr))
{
IUIAutomationTextPattern* pattern;
pAtMouse->GetCurrentPatternAs(UIA_TextPatternId, IID_IUIAutomationTextPattern,(void**)&pattern);
//TODO
wprintf(L"Element's Name: %s \n", name);
SysFreeString(name);
}
// Get the element's Control Type (in the current languange)
// and print it
BSTR controlType;
hr = pAtMouse->get_CurrentLocalizedControlType(&controlType);
if (SUCCEEDED(hr))
{
wprintf(L"Element's Control Type: %s \n", controlType);
SysFreeString(controlType);
}
// Clean up our COM pointers
pAtMouse->Release();
return hr;
}
int main(int argc, TCHAR* argv[])
{
// Initialize COM and create the main Automation object
IUIAutomation* g_pAutomation;
CoInitialize(NULL);
HRESULT hr = CoCreateInstance(__uuidof(CUIAutomation), NULL,
CLSCTX_INPROC_SERVER, __uuidof(IUIAutomation),
(void**)&g_pAutomation);
if (FAILED(hr))
return (hr);
bool quit = false;
while (!quit)
{
SHORT leftControlMod = GetAsyncKeyState(VK_LCONTROL);
if (leftControlMod != 0)
{
Element(g_pAutomation);
}
quit = GetAsyncKeyState(VK_ESCAPE);
}
g_pAutomation->Release();
CoUninitialize();
return 0;
}

Invalid Handle when using SetConsoleWindowInfo

I'm new to C++ and decided to challenge myself with a small console game. To avoid typical flickering.
Fromm what I got from MSDN docs I should be using a Console Buffer, but I took it easy and started from simple things like changing Window title and resizing it.
The small program I wrote was meant to do just that, but for some reason I get Error Code 6 (should be "invalid handle") when I execute the SetConsoleWindowInfo.
Anyone who can point me in the right direction with this? Thank you in advance
#include <windows.h>
#include <stdio.h>
#include <iostream>
HANDLE wHandle, bHandle;
SMALL_RECT wSize = { 0,0,100,100 };
int main() {
wHandle = GetConsoleWindow();
if (wHandle == NULL) {
printf("Handle is Null");
}
SetConsoleTitle(L"NewTitle");
if (!SetConsoleWindowInfo(wHandle, TRUE, &wSize)) {
printf("SetConsoleWindowInfo (%d)\n", GetLastError());
}
getchar();
return 0;
}
Maybe this will help:
#include <windows.h>
#include <stdio.h>
#include <iostream>
HANDLE wHandle, bHandle;
//SMALL_RECT wSize = { 0,0,100,100 }; // If SetConsoleWindow fails with code 87, then this is too big!
SMALL_RECT wSize = { 0,0,60,20 }; // Works on my screen!
int main() {
// wHandle = GetConsoleWindow();
wHandle = GetStdHandle(STD_OUTPUT_HANDLE); // See comment by RbMm
if (wHandle == NULL) {
printf("Handle is Null");
}
// SetConsoleTitle(L"NewTitle"); // Don't use a wide character string!
SetConsoleTitle("NewTitle");
if (!SetConsoleWindowInfo(wHandle, TRUE, &wSize)) {
printf("SetConsoleWindowInfo (%d)\n", GetLastError());
}
getchar();
return 0;
}
Feel free to ask, if you don't understand anything I've changed (or why I've changed it), but the comments address some of the issues.

How to play audio using Sink Writer from Microsoft Media Foundation

I'm trying to create an audio visualizer using Microsoft Media Foundation. For this I need to intercept the samples and simultaneously play them. Using a Media Session with Topology and a sample-grabber sink seems impractical and over-complicated, hence I'm trying to use a combination of a Sink Reader and Sink Writer for this (see the right half of the image on Overview of the Media Foundation Architecture). Unfortunately, Audio/Video Playback does not really explain how to do this. The book Developing Microsoft Media Foundation Applications contains a source-to-sink loop on page 92, but that still does not really help me.
Creating the Source Reader works fine and I'm reading nonzero samples. Writing them to the Sink Writer (which uses the Streaming Audio Renderer) does not give me any errors, but I don't hear anything. I tried multiple things like selecting other media types and explicitly selecting the rendering device (although I only have one, as it indicated), but to no avail. Note that playing audio using a Media Session works fine, though!
I based my code on this question: Play audio from file to speaker with Media Foundation.
This is my code at this moment:
#include <iostream>
#include <cassert>
#include <mfidl.h>
#include <mfapi.h>
#include <mfreadwrite.h>
#include <Mferror.h>
#pragma comment(lib, "mf")
#pragma comment(lib, "mfplat")
#pragma comment(lib, "mfreadwrite")
#include <winrt/base.h>
#pragma comment(lib, "windowsapp")
void winHr(const HRESULT result) { winrt::check_hresult(result); }
template<class T>
struct ComPtr : winrt::com_ptr<T>
{
auto operator&() noexcept { return this->put(); }
operator T*() noexcept
{
assert(this->get());
return this->get();
}
};
int main() noexcept
{
winHr(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
winHr(MFStartup(MF_VERSION));
{
ComPtr<IMFSourceReader> reader;
winHr(MFCreateSourceReaderFromURL(
LR"(test.wav)",
nullptr, &reader));
constexpr auto inStreamIndex = MF_SOURCE_READER_FIRST_AUDIO_STREAM;
// Select only the audio stream
winHr(reader->SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS, false));
winHr(reader->SetStreamSelection(inStreamIndex, true));
ComPtr<IMFMediaSink> mediaSink;
winHr(MFCreateAudioRenderer(nullptr, &mediaSink));
ComPtr<IMFSinkWriter> writer;
{
ComPtr<IMFStreamSink> streamSink;
winHr(mediaSink->GetStreamSinkByIndex(0, &streamSink));
ComPtr<IMFMediaTypeHandler> typeHandler;
winHr(streamSink->GetMediaTypeHandler(&typeHandler));
ComPtr<IMFMediaType> inputType;
winHr(reader->GetCurrentMediaType(inStreamIndex, &inputType));
ComPtr<IMFMediaType> closestSupportedType;
const auto result = typeHandler->IsMediaTypeSupported(inputType, &closestSupportedType);
if (result == MF_E_INVALIDMEDIATYPE)
{
if (!closestSupportedType)
{
std::cerr << "Media type not supported" << std::endl;
winHr(mediaSink->Shutdown());
goto end; //:o
}
winHr(reader->SetCurrentMediaType(inStreamIndex, nullptr, closestSupportedType));
winHr(typeHandler->SetCurrentMediaType(closestSupportedType));
winHr(MFCreateSinkWriterFromMediaSink(mediaSink, nullptr, &writer));
winHr(writer->SetInputMediaType(0, closestSupportedType, nullptr));
}
else {
winHr(result);
winHr(reader->SetCurrentMediaType(inStreamIndex, nullptr, inputType));
winHr(typeHandler->SetCurrentMediaType(inputType));
winHr(MFCreateSinkWriterFromMediaSink(mediaSink, nullptr, &writer));
winHr(writer->SetInputMediaType(0, inputType, nullptr));
}
}
winHr(writer->BeginWriting());
while (true)
{
ComPtr<IMFSample> sample;
DWORD streamFlags;
MFTIME timestamp;
winHr(reader->ReadSample(inStreamIndex, 0, nullptr, &streamFlags, &timestamp, &sample));
if (streamFlags & MF_SOURCE_READERF_ENDOFSTREAM)
{
winHr(writer->NotifyEndOfSegment(0));
break;
}
if (streamFlags & MF_SOURCE_READERF_STREAMTICK)
winHr(writer->SendStreamTick(0, timestamp));
if (!sample) continue;
winHr(sample->SetSampleTime(timestamp));
winHr(writer->WriteSample(0, sample));
}
winHr(writer->Flush(0));
std::cout << "(Press enter to stop)" << std::endl;
std::cin.get();
winHr(writer->Finalize());
writer.attach(nullptr);
winHr(mediaSink->Shutdown());
}
end:
winHr(MFShutdown());
CoUninitialize();
}
Just to be clear: when I run this it prints (Press enter to stop) and I can hear from the noise (read: distortions from electronic signals) from my headphones that I can deduce that for a short moment an audio port was opened and then closed, but no actual audio is played. How can I get this to work?
Edit 1: I just fixed that if result != MF_E_INVALIDMEDIATYPE I didn't set the media type, but now I often (but not always, for some reason) get MF_E_TOPO_CODEC_NOT_FOUND at the line winHr(writer->SetInputMediaType(0, inputType, nullptr));. Why would this be? (Still no audio is played in any case.)
Edit 2: Apparently it matters when I create the writer, so now I do that only at the last moment, but now I get the "Media type not supported" error. Maybe I need to manually pick some media type but I will look in to this later -- unless someone knows the answer.
I modified your code to work differently in the following manner:
1. Enumerates the Audio Sink output media types, until it finds a supported one.
2. Sets this media type to the Reader in order to force it to use Audio Resampler DSP (this is what IMFMediaTopology does).
Here is the code, it plays back the input wav file properly. Let me know if it works for you.
#include <iostream>
#include <cassert>
#include <mfidl.h>
#include <mfapi.h>
#include <mfreadwrite.h>
#include <Mferror.h>
#pragma comment(lib, "mf")
#pragma comment(lib, "mfplat")
#pragma comment(lib, "mfreadwrite")
#include <winrt/base.h>
#pragma comment(lib, "windowsapp")
void winHr(const HRESULT result) { winrt::check_hresult(result); }
template<class T>
struct ComPtr : winrt::com_ptr<T>
{
auto operator&() noexcept { return this->put(); }
operator T*() noexcept
{
assert(this->get());
return this->get();
}
};
int main() noexcept
{
winHr(CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE));
winHr(MFStartup(MF_VERSION));
{
ComPtr<IMFSourceReader> reader;
winHr(MFCreateSourceReaderFromURL(
LR"(test.wav)",
nullptr, &reader));
constexpr auto inStreamIndex = MF_SOURCE_READER_FIRST_AUDIO_STREAM;
// Select only the audio stream
winHr(reader->SetStreamSelection(MF_SOURCE_READER_ALL_STREAMS, false));
winHr(reader->SetStreamSelection(inStreamIndex, true));
ComPtr<IMFMediaSink> mediaSink;
winHr(MFCreateAudioRenderer(nullptr, &mediaSink));
ComPtr<IMFSinkWriter> writer;
{
ComPtr<IMFStreamSink> streamSink;
winHr(mediaSink->GetStreamSinkByIndex(0, &streamSink));
ComPtr<IMFMediaTypeHandler> typeHandler;
winHr(streamSink->GetMediaTypeHandler(&typeHandler));
DWORD dwCount = 0;
ComPtr<IMFMediaType> inputType;
winHr(typeHandler->GetMediaTypeCount(&dwCount));
for (INT i = 0; i < dwCount; i++)
{
inputType.attach(nullptr);
winHr(typeHandler->GetMediaTypeByIndex(i, &inputType));
if (SUCCEEDED(typeHandler->IsMediaTypeSupported(inputType, NULL)))
break;
}
//ComPtr<IMFMediaType> inputType;
//winHr(reader->GetCurrentMediaType(inStreamIndex, &inputType));
winHr(reader->SetCurrentMediaType(inStreamIndex, NULL, inputType));
//ComPtr<IMFMediaType> closestSupportedType;
//const auto result = typeHandler->IsMediaTypeSupported(inputType, &closestSupportedType);
//if (result == MF_E_INVALIDMEDIATYPE)
//{
// if (!closestSupportedType)
// {
// std::cerr << "Media type not supported" << std::endl;
// winHr(mediaSink->Shutdown());
// goto end; //:o
// }
// winHr(reader->SetCurrentMediaType(inStreamIndex, nullptr, closestSupportedType));
// winHr(typeHandler->SetCurrentMediaType(closestSupportedType));
// winHr(MFCreateSinkWriterFromMediaSink(mediaSink, nullptr, &writer));
// winHr(writer->SetInputMediaType(0, closestSupportedType, nullptr));
//}
//else
{
//winHr(result);
//winHr(reader->SetCurrentMediaType(inStreamIndex, nullptr, inputType));
winHr(typeHandler->SetCurrentMediaType(inputType));
winHr(MFCreateSinkWriterFromMediaSink(mediaSink, nullptr, &writer));
winHr(writer->SetInputMediaType(0, inputType, nullptr));
}
}
winHr(writer->BeginWriting());
while (true)
{
ComPtr<IMFSample> sample;
DWORD streamFlags;
MFTIME timestamp;
winHr(reader->ReadSample(inStreamIndex, 0, nullptr, &streamFlags, &timestamp, &sample));
if (streamFlags & MF_SOURCE_READERF_ENDOFSTREAM)
{
winHr(writer->NotifyEndOfSegment(0));
break;
}
if (streamFlags & MF_SOURCE_READERF_STREAMTICK)
winHr(writer->SendStreamTick(0, timestamp));
if (!sample)
continue;
// SetSampleTime is redundant
//winHr(sample->SetSampleTime(timestamp));
winHr(writer->WriteSample(0, sample));
}
// Flush shouldn't be called!
// winHr(writer->Flush(0));
std::cout << "(Press enter to stop)" << std::endl;
std::cin.get();
winHr(writer->Finalize());
writer.attach(nullptr);
winHr(mediaSink->Shutdown());
}
end:
winHr(MFShutdown());
CoUninitialize();
}
This code works just fine for me with wav files (Win7, default sound card) :
//----------------------------------------------------------------------------------------------
// Main.cpp
//----------------------------------------------------------------------------------------------
#pragma once
#define WIN32_LEAN_AND_MEAN
#define STRICT
#pragma comment(lib, "mfplat")
#pragma comment(lib, "mfreadwrite")
#pragma comment(lib, "mf")
#pragma comment(lib, "mfuuid")
//----------------------------------------------------------------------------------------------
// Microsoft Windows SDK for Windows 7
#include <WinSDKVer.h>
#include <new>
#include <windows.h>
#include <strsafe.h>
#include <mfapi.h>
#include <mfidl.h>
#include <mferror.h>
#include <mfreadwrite.h>
template <class T> inline void SAFE_RELEASE(T*& p){
if(p){
p->Release();
p = NULL;
}
}
#define AUDIO_FILE L"C:\\Project\\Media\\Audio\\test.wav"
HRESULT ProcessAudio(const WCHAR*);
void main(){
HRESULT hr = CoInitializeEx(NULL, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
if(SUCCEEDED(hr)){
hr = MFStartup(MF_VERSION, MFSTARTUP_LITE);
if(SUCCEEDED(hr)){
hr = ProcessAudio(AUDIO_FILE);
hr = MFShutdown();
}
CoUninitialize();
}
}
HRESULT ProcessAudio(const WCHAR*){
IMFSourceReader* pSourceReader = NULL;
IMFMediaType* pType = NULL;
DWORD dwMediaTypeIndex = 0;
IMFMediaSink* pAudioSink = NULL;
IMFStreamSink* pStreamSink = NULL;
IMFMediaTypeHandler* pMediaTypeHandler = NULL;
IMFSinkWriter* pSinkWriter = NULL;
HRESULT hr = MFCreateSourceReaderFromURL(AUDIO_FILE, NULL, &pSourceReader);
// Check native media type
if(SUCCEEDED(hr))
hr = pSourceReader->GetNativeMediaType((DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM, dwMediaTypeIndex, &pType);
SAFE_RELEASE(pType);
// Get current media type
if(SUCCEEDED(hr))
hr = pSourceReader->GetCurrentMediaType(dwMediaTypeIndex, &pType);
if(SUCCEEDED(hr))
hr = MFCreateAudioRenderer(NULL, &pAudioSink);
if(SUCCEEDED(hr))
hr = pAudioSink->GetStreamSinkByIndex(0, &pStreamSink);
if(SUCCEEDED(hr))
hr = pStreamSink->GetMediaTypeHandler(&pMediaTypeHandler);
if(FAILED(hr = pMediaTypeHandler->IsMediaTypeSupported(pType, NULL))){
SAFE_RELEASE(pType);
// This is a compatible type with my soundcard
// MF_MT_MAJOR_TYPE MFMediaType_Audio
// MF_MT_SUBTYPE MFAudioFormat_PCM
// MF_MT_AUDIO_NUM_CHANNELS 2
// MF_MT_AUDIO_SAMPLES_PER_SECOND 48000
// MF_MT_AUDIO_BLOCK_ALIGNMENT 4
// MF_MT_AUDIO_AVG_BYTES_PER_SECOND 192000
// MF_MT_AUDIO_BITS_PER_SAMPLE 16
// MF_MT_ALL_SAMPLES_INDEPENDENT 1
// MF_MT_AUDIO_PREFER_WAVEFORMATEX 1
hr = MFCreateMediaType(&pType);
if(SUCCEEDED(hr))
hr = pType->SetGUID(MF_MT_MAJOR_TYPE, MFMediaType_Audio);
if(SUCCEEDED(hr))
hr = pType->SetGUID(MF_MT_SUBTYPE, MFAudioFormat_PCM);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_NUM_CHANNELS, 2);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_SAMPLES_PER_SECOND, 48000);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_BLOCK_ALIGNMENT, 4);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_AVG_BYTES_PER_SECOND, 192000);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_BITS_PER_SAMPLE, 16);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_ALL_SAMPLES_INDEPENDENT, TRUE);
if(SUCCEEDED(hr))
hr = pType->SetUINT32(MF_MT_AUDIO_PREFER_WAVEFORMATEX, TRUE);
}
if(SUCCEEDED(hr))
hr = pMediaTypeHandler->SetCurrentMediaType(pType);
if(SUCCEEDED(hr))
hr = MFCreateSinkWriterFromMediaSink(pAudioSink, NULL, &pSinkWriter);
if(SUCCEEDED(hr))
hr = pSinkWriter->BeginWriting();
BOOL bProcess = (hr == S_OK ? TRUE : FALSE);
DWORD streamIndex;
DWORD flags;
LONGLONG llTimeStamp;
IMFSample* pSample = NULL;
while(bProcess){
hr = pSourceReader->ReadSample((DWORD)MF_SOURCE_READER_FIRST_AUDIO_STREAM, 0, &streamIndex, &flags, &llTimeStamp, &pSample);
if(SUCCEEDED(hr) && (flags == 0)){
if(pSample){
hr = pSinkWriter->WriteSample(0, pSample);
SAFE_RELEASE(pSample);
}
}
else{
bProcess = FALSE;
}
}
if(pSinkWriter)
pSinkWriter->Finalize();
if(pAudioSink)
pAudioSink->Shutdown();
SAFE_RELEASE(pSample);
SAFE_RELEASE(pSinkWriter);
SAFE_RELEASE(pMediaTypeHandler);
SAFE_RELEASE(pStreamSink);
SAFE_RELEASE(pAudioSink);
SAFE_RELEASE(pType);
SAFE_RELEASE(pSourceReader);
return hr;
}
If you face problem with MF_E_TOPO_CODEC_NOT_FOUND, share your file. Perhaps extra code is needed in this case.
EDIT
Do you have more than one sound card ?
Share your audio file, so we can see what's going on.
My little hack with Sleep(40), is just here to tell you that doing "while(true)" without pausing have no sens (your processor is working too much). Off course 40 should be better decided. 40 is the minimum processing time processor preemption on windows OS. That my choice for this sample code. We can talk about the best way to choose this value. I'm waiting for your suggestion.

{app.exe!_com_error::`vector deleting destructor'(unsigned int)}

I am getting exception while creating MSMQqueue in Visual Studio 2017, find the code and exception details below:
Exception details :
app.exe!`queue::CreateQueue'::`1'::catch$3() Line 56 C++ Symbols loaded.
Please suggest the queue for implementing serial port read and write.
queue.cpp
#include "stdafx.h"
#include "MSMQ_Queue.h"
#import "mqoa.dll"
using namespace MSMQ;
queue::queue() {}
queue::~queue() {}
HRESULT queue::CreateQueue(WCHAR *wszPathName)
{
HRESULT hr = S_OK;
if (wszPathName == NULL)
{
return MQ_ERROR_INVALID_PARAMETER;
}
try
{
IMSMQQueueInfoPtr pInfo("MSMQ.MSMQQueueInfo");
// Set the queue's path name and label.
pInfo->PathName = wszPathName;
pInfo->Label = "TestQueue";
// Create the queue.
**pInfo->Create();**//Hitting exception at this point
WCHAR wszMessage[1024] = { 0 };
}
catch (const _com_error& comerr)
{
hr = comerr.Error();
WCHAR wszMessage[2048] = { 0 };
}
return hr;
}
main.cpp
#include "stdafx.h"
#include"queue.h"
#include <stdio.h> // for printf
int main()
{
wchar_t name[] = L".\\vniqueue";
queue msmqueue;
//CoInitialize(0);
OleInitialize(NULL);
HRESULT returnValue = msmqueue.CreateQueue(name);
getchar();
return 0;
}
Exception create queue
Finally I found solutions for this..
I have given public path instead of private pat. Changed “.//queuename” to .//private$//queuename”.

Why can I not acquire the keyboard with DirectInput?

I just started getting into DirectInput today, using DirectInput8 with MinGW on Windows 7 Ultimate N. I started off with a simple program to report which keys are currently down every second (just codes, not readable keys). However, I can't even get as far as acquiring the keyboard before it errors out:
#define _WIN32_WINNT 0x0601
#include <dinput.h>
//link to dinput8.lib and dxguid.lib
int main() {
IDirectInput8 *dinput;
DirectInput8Create(GetModuleHandle(nullptr), DIRECTINPUT_VERSION, IID_IDirectInput8, (void **)&dinput, nullptr);
IDirectInputDevice8 *kb;
dinput->CreateDevice(GUID_SysKeyboard, &kb, nullptr);
kb->SetDataFormat(&c_dfDIKeyboard);
kb->SetCooperativeLevel(GetConsoleWindow(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
kb->Acquire(); //fails with DIERR_INVALIDPARAM
}
I omitted error checking, but what happens is that every call succeeds (by judgement of the FAILED macro) up to Acquire(). That call fails with the error DIERR_INVALIDPARAM. I looked on the MSDN pages and across the web, but I can't find any reason it would fail with that based on everything before it present and working.
For good measure, I also tried looping the Acquire() call until it succeeded and then played around with windows and the keyboard while it was running, but the program never successfully acquired the keyboard in all the time it was running. How can I successfully acquire the keyboard?
Experimenting with direct input in a console program for the keyboard and joystick
It is not necessary to have a handle to a window to use direct input. You can just use null in the parameter for a handle to a window.
Instead of:
kb->SetCooperativeLevel(GetConsoleWindow(), DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
Use:
kb->SetCooperativeLevel(NULL, DISCL_FOREGROUND | DISCL_NONEXCLUSIVE);
Here is an example program that uses direct input to display the keys 'a' and 'd' when those keys are pressed. It will repeat those keys when they are held for 300 milliseconds. The example program is also a good example of a high resolution counter. There is no need to add in properties in Visual Studio to add the libraries dinput8.lib and dxguid.lib. The #pragma comment code lines at the top of the program do that for you.
#include <dinput.h>
#include <iostream>
#include <Windows.h>
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")
using std::cout;
using std::endl;
LPDIRECTINPUT8 di;
LPDIRECTINPUTDEVICE8 keyboard;
class CTimer
{
public:
CTimer() {
QueryPerformanceFrequency(&mqFreq);
}
~CTimer() {}
void Start() {
QueryPerformanceCounter(&mqStart);
}
void End() {
QueryPerformanceCounter(&mqEnd);
}
double GetTimeInSeconds() {
return (mqEnd.QuadPart - mqStart.QuadPart)/(double)mqFreq.QuadPart;
}
double GetTimeInMilliseconds() {
return (1.0e3*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
double GetTimeInMicroseconds() {
return (1.0e6*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
double GetTimeInNanoseconds() {
return (1.0e9*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
private:
LARGE_INTEGER mqStart;
LARGE_INTEGER mqEnd;
LARGE_INTEGER mqFreq;
};
HRESULT initializedirectinput8() {
HRESULT hr;
// Create a DirectInput device
if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
IID_IDirectInput8, (VOID**)&di, NULL))) {
return hr;
}
}
void createdikeyboard() {
di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
keyboard->SetDataFormat(&c_dfDIKeyboard);
keyboard->SetCooperativeLevel(NULL,DISCL_FOREGROUND | DISCL_EXCLUSIVE);
keyboard->Acquire();
}
void destroydikeyboard() {
keyboard->Unacquire();
keyboard->Release();
}
#define keydown(name,key) (name[key] & 0x80)
void main() {
HRESULT hr;
BYTE dikeys[256];
CTimer timeint;
CTimer timekeywaspressedclass;
double gettime;
double lastkeywasa=false;
double timekeywaspressed=0;
bool lasttimetherewasakeypress=false;
bool akeywaspressed=false;
initializedirectinput8();
createdikeyboard();
hr=keyboard->GetDeviceState(256,dikeys);
timeint.Start();
while (!keydown(dikeys,DIK_ESCAPE)) {
timeint.End();
gettime=timeint.GetTimeInMilliseconds();
if (gettime >=5) {
hr=keyboard->GetDeviceState(256,dikeys);
akeywaspressed=false;
if (keydown(dikeys,DIK_A)) {
akeywaspressed=true;
if (timekeywaspressed >=300) {
cout << "a";
lasttimetherewasakeypress=false;
}
}
if (keydown(dikeys,DIK_D)) {
akeywaspressed=true;
if (timekeywaspressed >=300) {
cout << "d";
lasttimetherewasakeypress=false;
}
}
if (lasttimetherewasakeypress==false && akeywaspressed==true) {
timekeywaspressedclass.Start();
timekeywaspressed=0;
lasttimetherewasakeypress=true;
}
if (lasttimetherewasakeypress==true && akeywaspressed==true) {
timekeywaspressedclass.End();
gettime=timekeywaspressedclass.GetTimeInMilliseconds();
timekeywaspressed+=gettime;
timekeywaspressedclass.Start();
}
if (akeywaspressed==false) {
lasttimetherewasakeypress=false;
timekeywaspressed=0;
}
} // end if (gettime >=5)
} // end while
destroydikeyboard();
} // end main
Here is an example console program for the joystick.
#include <dinput.h>
#include <iostream>
#include <Windows.h>
#pragma comment(lib,"dinput8.lib")
#pragma comment(lib,"dxguid.lib")
using std::cout;
using std::endl;
LPDIRECTINPUT8 di;
LPDIRECTINPUTDEVICE8 joystick;
LPDIRECTINPUTDEVICE8 keyboard;
DIJOYSTATE2 js;
BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE* instance, VOID* context);
BOOL CALLBACK enumAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, VOID* context);
HRESULT selectjoystick() {
HRESULT hr;
// Look for the first simple joystick we can find.
if (FAILED(hr = di->EnumDevices(DI8DEVCLASS_GAMECTRL, enumCallback,
NULL, DIEDFL_ATTACHEDONLY))) {
return hr;
}
// Make sure we got a joystick
if (joystick == NULL) {
// printf("Joystick not found.\n");
return E_FAIL;
}
}
DIDEVCAPS capabilities;
HRESULT setjoystickproperties() {
HRESULT hr;
// Set the data format to "simple joystick" - a predefined data format
//
// A data format specifies which controls on a device we are interested in,
// and how they should be reported. This tells DInput that we will be
// passing a DIJOYSTATE2 structure to IDirectInputDevice::GetDeviceState().
if (FAILED(hr = joystick->SetDataFormat(&c_dfDIJoystick2))) {
return hr;
}
// Set the cooperative level to let DInput know how this device should
// interact with the system and with other DInput applications.
if (FAILED(hr = joystick->SetCooperativeLevel(NULL, DISCL_EXCLUSIVE |
DISCL_FOREGROUND))) {
return hr;
}
// Determine how many axis the joystick has (so we don't error out setting
// properties for unavailable axis)
capabilities.dwSize = sizeof(DIDEVCAPS);
if (FAILED(hr = joystick->GetCapabilities(&capabilities))) {
return hr;
}
}
BOOL CALLBACK enumCallback(const DIDEVICEINSTANCE* instance, VOID* context)
{
HRESULT hr;
// Obtain an interface to the enumerated joystick.
hr = di->CreateDevice(instance->guidInstance, &joystick, NULL);
// If it failed, then we can't use this joystick. (Maybe the user unplugged
// it while we were in the middle of enumerating it.)
if (FAILED(hr)) {
return DIENUM_CONTINUE;
}
// Stop enumeration. Note: we're just taking the first joystick we get. You
// could store all the enumerated joysticks and let the user pick.
return DIENUM_STOP;
}
HRESULT enumaxes() {
HRESULT hr;
// Enumerate the axes of the joyctick and set the range of each axis. Note:
// we could just use the defaults, but we're just trying to show an example
// of enumerating device objects (axes, buttons, etc.).
if (FAILED(hr = joystick->EnumObjects(enumAxesCallback, NULL, DIDFT_AXIS))) {
return hr;
}
}
BOOL CALLBACK enumAxesCallback(const DIDEVICEOBJECTINSTANCE* instance, VOID* context)
{
HWND hDlg = (HWND)context;
DIPROPRANGE propRange;
propRange.diph.dwSize = sizeof(DIPROPRANGE);
propRange.diph.dwHeaderSize = sizeof(DIPROPHEADER);
propRange.diph.dwHow = DIPH_BYID;
propRange.diph.dwObj = instance->dwType;
propRange.lMin = -1000;
propRange.lMax = +1000;
// Set the range for the axis
if (FAILED(joystick->SetProperty(DIPROP_RANGE, &propRange.diph))) {
return DIENUM_STOP;
}
return DIENUM_CONTINUE;
}
HRESULT polljoy() {
HRESULT hr;
if (joystick == NULL) {
return S_OK;
}
// Poll the device to read the current state
hr = joystick->Poll();
if (FAILED(hr)) {
// DInput is telling us that the input stream has been
// interrupted. We aren't tracking any state between polls, so
// we don't have any special reset that needs to be done. We
// just re-acquire and try again.
hr = joystick->Acquire();
while (hr == DIERR_INPUTLOST) {
hr = joystick->Acquire();
}
// If we encounter a fatal error, return failure.
if ((hr == DIERR_INVALIDPARAM) || (hr == DIERR_NOTINITIALIZED)) {
return E_FAIL;
}
// If another application has control of this device, return successfully.
// We'll just have to wait our turn to use the joystick.
if (hr == DIERR_OTHERAPPHASPRIO) {
return S_OK;
}
}
// Get the input's device state
if (FAILED(hr = joystick->GetDeviceState(sizeof(DIJOYSTATE2), &js))) {
return hr; // The device should have been acquired during the Poll()
}
return S_OK;
}
class CTimer
{
public:
CTimer() {
QueryPerformanceFrequency(&mqFreq);
}
~CTimer() {}
void Start() {
QueryPerformanceCounter(&mqStart);
}
void End() {
QueryPerformanceCounter(&mqEnd);
}
double GetTimeInSeconds() {
return (mqEnd.QuadPart - mqStart.QuadPart)/(double)mqFreq.QuadPart;
}
double GetTimeInMilliseconds() {
return (1.0e3*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
double GetTimeInMicroseconds() {
return (1.0e6*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
double GetTimeInNanoseconds() {
return (1.0e9*(mqEnd.QuadPart - mqStart.QuadPart))/mqFreq.QuadPart;
}
private:
LARGE_INTEGER mqStart;
LARGE_INTEGER mqEnd;
LARGE_INTEGER mqFreq;
};
HRESULT initializedirectinput8() {
HRESULT hr;
// Create a DirectInput device
if (FAILED(hr = DirectInput8Create(GetModuleHandle(NULL), DIRECTINPUT_VERSION,
IID_IDirectInput8, (VOID**)&di, NULL))) {
return hr;
}
}
void createdikeyboard() {
di->CreateDevice(GUID_SysKeyboard, &keyboard, NULL);
keyboard->SetDataFormat(&c_dfDIKeyboard);
keyboard->SetCooperativeLevel(NULL,DISCL_FOREGROUND | DISCL_EXCLUSIVE);
keyboard->Acquire();
}
void destroydikeyboard() {
keyboard->Unacquire();
keyboard->Release();
}
void closejoystick() {
if (joystick) {
joystick->Unacquire();
}
if (joystick) {
joystick->Release();
}
}
#define keydown(name,key) (name[key] & 0x80)
void main() {
HRESULT hr;
CTimer pollintclass;
hr=initializedirectinput8();
createdikeyboard();
hr=selectjoystick();
hr=setjoystickproperties();
hr=enumaxes();
bool endloop=false;
double gettime;
BYTE dikeys[256];
pollintclass.Start();
while (endloop==false) {
pollintclass.End();
gettime=pollintclass.GetTimeInMilliseconds();
if (gettime >=5) {
hr=keyboard->GetDeviceState(256,dikeys);
if (FAILED(hr))
keyboard->Acquire();
if (keydown(dikeys,DIK_ESCAPE))
endloop=true;
polljoy();
cout << "joy x-axis=" << js.lX << " " << "joy y-axis=" << js.lY << endl;
pollintclass.Start();
}
}
destroydikeyboard();
closejoystick();
}
Have you tried DISCL_BACKGROUND instead of DISCL_FOREGROUND ?
It actually happens that the error magically disappears when I change it from associating with the console window (which is visibly existent) to one I create in the SetCooperativeLevel() call. Why a console window can't be used I don't know, so I'll leave this unaccepted for a while in lieu of an answerer who does, but this does solve the problem.