Предполагается, что этот код выведет основной синусоидальный тон, но он выводит действительно мусорное аудио, которое соC++

Программы на C++. Форум разработчиков
Ответить
Anonymous
 Предполагается, что этот код выведет основной синусоидальный тон, но он выводит действительно мусорное аудио, которое со

Сообщение Anonymous »

Я пытаюсь настроить воспроизведение звука, используя DirectSound в C ++ в Windows: < /p>
#include
#include
#include
#include
#include

#define internal static
#define local_persist static
#define global_variable static

typedef int8_t int8;
typedef int16_t int16;
typedef int32_t int32;
typedef int64_t int64;
typedef int32 bool32;

typedef uint8_t uint8;
typedef uint16_t uint16;
typedef uint32_t uint32;
typedef uint64_t uint64;

typedef float real32;
typedef double real64;

const real32 Pi32 = 3.14159265359f;

struct win32_offscreen_buffer
{
BITMAPINFO Info;
void* Memory;
int Width;
int Height;
int Pitch;
int BytesPerPixel;
};

struct win32_window_dimension {
int Width;
int Height;
};

struct win32_sound_output
{
int SamplesPerSecond;
int ToneHz;
int16 ToneVolume;
uint32 RunningSampleIndex;
int WavePeriod;
int BytesPerSample;
int SecondaryBufferSize;
int LatencySampleCount;
bool SoundIsPlaying;
};

// XInput declarations
#define X_INPUT_GET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_STATE* pState)
#define X_INPUT_SET_STATE(name) DWORD WINAPI name(DWORD dwUserIndex, XINPUT_VIBRATION* pVibration)

typedef X_INPUT_GET_STATE(x_input_get_state);
typedef X_INPUT_SET_STATE(x_input_set_state);

X_INPUT_GET_STATE(XInputGetStateStub) { return ERROR_DEVICE_NOT_CONNECTED; }
X_INPUT_SET_STATE(XInputSetStateStub) { return ERROR_DEVICE_NOT_CONNECTED; }

global_variable x_input_get_state* XInputGetState_ = XInputGetStateStub;
global_variable x_input_set_state* XInputSetState_ = XInputSetStateStub;

// Macro redirection
#define XInputGetState XInputGetState_
#define XInputSetState XInputSetState_

// DirectSound declarations
#define DIRECT_SOUND_CREATE(name) HRESULT WINAPI name(LPCGUID, LPDIRECTSOUND*, LPUNKNOWN)
typedef DIRECT_SOUND_CREATE(direct_sound_create);

// Global Variables
global_variable bool GlobalRunning;
global_variable win32_offscreen_buffer GlobalBackBuffer;
global_variable LPDIRECTSOUNDBUFFER GlobalSecondaryBuffer;

//
// XInput loading
//
internal void
Win32LoadXInput(void)
{
HMODULE XInputLibrary = LoadLibraryA("xinput1_4.dll");
if (!XInputLibrary) { XInputLibrary = LoadLibraryA("xinput9_1_0.dll"); }
if (!XInputLibrary) { XInputLibrary = LoadLibraryA("xinput1_3.dll"); }

if (XInputLibrary)
{
XInputGetState = (x_input_get_state*)GetProcAddress(XInputLibrary, "XInputGetState");
if (!XInputGetState) { XInputGetState = XInputGetStateStub; }

XInputSetState = (x_input_set_state*)GetProcAddress(XInputLibrary, "XInputSetState");
if (!XInputSetState) { XInputSetState = XInputSetStateStub; }
}
}

//
// DirectSound initialization
//
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");

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)))
{
// Primary buffer (just for format)
DSBUFFERDESC BufferDescription = {};
BufferDescription.dwSize = sizeof(BufferDescription);
BufferDescription.dwFlags = DSBCAPS_PRIMARYBUFFER;

LPDIRECTSOUNDBUFFER PrimaryBuffer;
if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &PrimaryBuffer, 0)))
{
if (SUCCEEDED(PrimaryBuffer->SetFormat(&WaveFormat)))
{
OutputDebugStringA("Primary buffer format set.\n");
}
}

// Secondary buffer (actual sound)
BufferDescription.dwFlags = 0;
BufferDescription.dwBufferBytes = BufferSize;
BufferDescription.lpwfxFormat = &WaveFormat;
if (SUCCEEDED(DirectSound->CreateSoundBuffer(&BufferDescription, &GlobalSecondaryBuffer, 0)))
{
OutputDebugStringA("Secondary buffer created.\n");
}
else
{
OutputDebugStringA("ERROR: Failed to create secondary buffer\n");
GlobalSecondaryBuffer = NULL;
}
}
}
}
}

//
// Buffer management
//
internal win32_window_dimension
Win32GetWindowDimension(HWND Window)
{
win32_window_dimension Result;
RECT ClientRect;
GetClientRect(Window, &ClientRect);
Result.Width = ClientRect.right - ClientRect.left;
Result.Height = ClientRect.bottom - ClientRect.top;
return Result;
}

internal void
RenderWeirdGradient(win32_offscreen_buffer* Buffer, int BlueOffset, int GreenOffset)
{
uint8* Row = (uint8*)Buffer->Memory;
for (int Y = 0; Y < Buffer->Height; ++Y)
{
uint32* Pixel = (uint32*)Row;
for (int X = 0; X < Buffer->Width; ++X)
{
uint8 Blue = (X + BlueOffset);
uint8 Green = (Y + GreenOffset);
*Pixel++ = ((Green Pitch;
}
}

internal void
Win32ResizeDIBSection(win32_offscreen_buffer* Buffer, int Width, int Height)
{
if (Buffer->Memory)
{
VirtualFree(Buffer->Memory, 0, MEM_RELEASE);
}

Buffer->Width = Width;
Buffer->Height = Height;
Buffer->BytesPerPixel = 4;

Buffer->Info.bmiHeader.biSize = sizeof(Buffer->Info.bmiHeader);
Buffer->Info.bmiHeader.biWidth = Buffer->Width;
Buffer->Info.bmiHeader.biHeight = -Buffer->Height;
Buffer->Info.bmiHeader.biPlanes = 1;
Buffer->Info.bmiHeader.biBitCount = 32;
Buffer->Info.bmiHeader.biCompression = BI_RGB;

int BitmapMemorySize = (Buffer->Width * Buffer->Height) * Buffer->BytesPerPixel;
Buffer->Memory = VirtualAlloc(0, BitmapMemorySize, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE);
Buffer->Pitch = Width * Buffer->BytesPerPixel;
}

internal void
Win32DisplayBufferInWindow(win32_offscreen_buffer* Buffer, HDC DeviceContext, int WindowWidth, int WindowHeight)
{
StretchDIBits(DeviceContext,
0, 0, WindowWidth, WindowHeight,
0, 0, Buffer->Width, Buffer->Height,
Buffer->Memory,
&Buffer->Info,
DIB_RGB_COLORS, SRCCOPY);
}

//
// Sound Fill
//
internal void
Win32FillSoundBuffer(win32_sound_output* SoundOutput, DWORD BytesToLock, DWORD BytesToWrite)
{
VOID* Region1;
DWORD Region1Size;
VOID* Region2;
DWORD Region2Size;
if (SUCCEEDED(GlobalSecondaryBuffer->Lock(BytesToLock, BytesToWrite,
&Region1, &Region1Size,
&Region2, &Region2Size,
0)))
{
DWORD Region1SampleCount = Region1Size / SoundOutput->BytesPerSample;
DWORD Region2SampleCount = Region2Size / SoundOutput->BytesPerSample;

int16* SampleOut = (int16*)Region1;
for (DWORD SampleIndex = 0; SampleIndex < Region1SampleCount; ++SampleIndex)
{
real32 t = 2.0f * Pi32 * (real32)SoundOutput->RunningSampleIndex / (real32)SoundOutput->WavePeriod;
int16 SampleValue = (int16)(sinf(t) * SoundOutput->ToneVolume);
*SampleOut++ = SampleValue;
*SampleOut++ = SampleValue;
++SoundOutput->RunningSampleIndex;
}

SampleOut = (int16*)Region2;
for (DWORD SampleIndex = 0; SampleIndex < Region2SampleCount; ++SampleIndex)
{
real32 t = 2.0f * Pi32 * (real32)SoundOutput->RunningSampleIndex / (real32)SoundOutput->WavePeriod;
int16 SampleValue = (int16)(sinf(t) * SoundOutput->ToneVolume);
*SampleOut++ = SampleValue;
*SampleOut++ = SampleValue;
++SoundOutput->RunningSampleIndex;
}

GlobalSecondaryBuffer->Unlock(Region1, Region1Size, Region2, Region2Size);
}
}

//
// Window Procedure
//
LRESULT CALLBACK
Win32MainWindowCallback(HWND Window,
UINT Message,
WPARAM WParam,
LPARAM LParam)
{
LRESULT Result = 0;

switch (Message)
{
case WM_SIZE:
{
} break;

case WM_DESTROY:
{
GlobalRunning = false;
} break;

case WM_CLOSE:
{
GlobalRunning = false;
} break;

case WM_ACTIVATEAPP:
{
OutputDebugStringA("WM_ACTIVATEAPP\n");
} break;

case WM_PAINT:
{
PAINTSTRUCT Paint;
HDC DeviceContext = BeginPaint(Window, &Paint);
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(&GlobalBackBuffer, DeviceContext,
Dimension.Width, Dimension.Height);
EndPaint(Window, &Paint);
} break;

case WM_SYSKEYDOWN:
case WM_SYSKEYUP:
case WM_KEYDOWN:
case WM_KEYUP:
{
uint32 VKCode = WParam;
bool WasDown = ((LParam & (1 wButtons & XINPUT_GAMEPAD_DPAD_UP);
bool Down = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_DOWN);
bool Left = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_LEFT);
bool Right = (Pad->wButtons & XINPUT_GAMEPAD_DPAD_RIGHT);
bool Start = (Pad->wButtons & XINPUT_GAMEPAD_START);
bool Back = (Pad->wButtons & XINPUT_GAMEPAD_BACK);
bool LeftShoulder = (Pad->wButtons & XINPUT_GAMEPAD_LEFT_SHOULDER);
bool RightShoulder = (Pad->wButtons & XINPUT_GAMEPAD_RIGHT_SHOULDER);
bool AButton = (Pad->wButtons & XINPUT_GAMEPAD_A);
bool BButton = (Pad->wButtons & XINPUT_GAMEPAD_B);
bool XButton = (Pad->wButtons & XINPUT_GAMEPAD_X);
bool YButton = (Pad->wButtons & XINPUT_GAMEPAD_Y);

int16 StickX = Pad->sThumbLX;
int16 StickY = Pad->sThumbLY;

if (AButton)
{
YOffset += 2;
}
}
}

RenderWeirdGradient(&GlobalBackBuffer, XOffset, YOffset);

// Sound output
if (GlobalSecondaryBuffer) {
DWORD PlayCursor;
DWORD WriteCursor;
GlobalSecondaryBuffer->GetCurrentPosition(&PlayCursor, &WriteCursor);

DWORD ByteToLock = (LastPlayCursor * SoundOutput.BytesPerSample) % SoundOutput.SecondaryBufferSize;

// Improved target cursor calculation
DWORD TargetCursor = ((PlayCursor +
(SoundOutput.LatencySampleCount * SoundOutput.BytesPerSample)) %
SoundOutput.SecondaryBufferSize);

DWORD BytesToWrite;
if (ByteToLock > TargetCursor)
{
BytesToWrite = SoundOutput.SecondaryBufferSize - ByteToLock;
BytesToWrite += TargetCursor;
}
else
{
BytesToWrite = TargetCursor - ByteToLock;
}

Win32FillSoundBuffer(&SoundOutput, ByteToLock, BytesToWrite);
LastPlayCursor = PlayCursor;
}

// Display
win32_window_dimension Dimension = Win32GetWindowDimension(Window);
Win32DisplayBufferInWindow(&GlobalBackBuffer, DeviceContext,
Dimension.Width, Dimension.Height);

++XOffset;
}
}
else
{
// Logging
}
}
else
{
// Logging
}

return 0;
}
< /code>
Аудио в основном работает, но я получаю настоящий звук мусора, который, кажется, не имеет какого -либо шаблона. < /p>
Где ошибка? Мой буфер блокирую математику верна?


Подробнее здесь: https://stackoverflow.com/questions/796 ... s-a-really
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «C++»