Audio Handling and simple GUI

- Audio Playback crashes the App due to an access violation rn
- GUI will get a overhaul later, might switch to QT
- SDK later on
This commit is contained in:
ApfelTeeSaft
2024-12-02 08:21:59 +01:00
parent 72875f8bdb
commit 9c5ef49636
10 changed files with 603 additions and 0 deletions
+31
View File
@@ -0,0 +1,31 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.11.35431.28
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "ApfelDAW", "ApfelDAW\ApfelDAW.vcxproj", "{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Debug|x64.ActiveCfg = Debug|x64
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Debug|x64.Build.0 = Debug|x64
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Debug|x86.ActiveCfg = Debug|Win32
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Debug|x86.Build.0 = Debug|Win32
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Release|x64.ActiveCfg = Release|x64
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Release|x64.Build.0 = Release|x64
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Release|x86.ActiveCfg = Release|Win32
{2ECCB40B-E250-4F78-87B2-2BEB3D59E571}.Release|x86.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {3779F40C-D8D6-4877-8316-981E5772D63B}
EndGlobalSection
EndGlobal
+144
View File
@@ -0,0 +1,144 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|Win32">
<Configuration>Release</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|x64">
<Configuration>Debug</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Release|x64">
<Configuration>Release</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
</ItemGroup>
<PropertyGroup Label="Globals">
<VCProjectVersion>17.0</VCProjectVersion>
<Keyword>Win32Proj</Keyword>
<ProjectGuid>{2eccb40b-e250-4f78-87b2-2beb3d59e571}</ProjectGuid>
<RootNamespace>ApfelDAW</RootNamespace>
<WindowsTargetPlatformVersion>10.0</WindowsTargetPlatformVersion>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="Shared">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>stdcpplatest</LanguageStandard>
</ClCompile>
<Link>
<SubSystem>Windows</SubSystem>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClInclude Include="daw.h" />
<ClInclude Include="gui.h" />
<ClInclude Include="trackeditor.h" />
</ItemGroup>
<ItemGroup>
<ClCompile Include="daw.cpp" />
<ClCompile Include="gui.cpp" />
<ClCompile Include="main.cpp" />
<ClCompile Include="trackeditor.cpp" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
</Project>
+42
View File
@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier>
<Extensions>cpp;c;cc;cxx;c++;cppm;ixx;def;odl;idl;hpj;bat;asm;asmx</Extensions>
</Filter>
<Filter Include="Header Files">
<UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier>
<Extensions>h;hh;hpp;hxx;h++;hm;inl;inc;ipp;xsd</Extensions>
</Filter>
<Filter Include="Resource Files">
<UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier>
<Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions>
</Filter>
</ItemGroup>
<ItemGroup>
<ClInclude Include="daw.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="gui.h">
<Filter>Header Files</Filter>
</ClInclude>
<ClInclude Include="trackeditor.h">
<Filter>Header Files</Filter>
</ClInclude>
</ItemGroup>
<ItemGroup>
<ClCompile Include="daw.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="gui.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="main.cpp">
<Filter>Source Files</Filter>
</ClCompile>
<ClCompile Include="trackeditor.cpp">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
</Project>
+148
View File
@@ -0,0 +1,148 @@
#include "daw.h"
#include <sndfile.h>
#include <portaudio.h>
#include <stdexcept>
#include <iostream>
#include <thread>
#include <string>
static int audioCallback(const void* inputBuffer, void* outputBuffer,
unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags, void* userData) {
auto* track = reinterpret_cast<Track*>(userData);
auto* out = static_cast<float*>(outputBuffer);
static size_t position = 0;
size_t remaining = track->audioData.size() - position;
size_t toCopy = std::min<size_t>(framesPerBuffer * track->channels, remaining);
std::copy(track->audioData.begin() + position, track->audioData.begin() + position + toCopy, out);
position += toCopy;
if (toCopy < framesPerBuffer * track->channels) {
std::fill(out + toCopy, out + framesPerBuffer * track->channels, 0.0f);
position = 0;
return paComplete;
}
return paContinue;
}
void DAW::addTrack(const std::string& filePath) {
Track track;
loadAudio(filePath, track);
tracks.push_back(track);
}
void DAW::removeTrack(int index) {
if (index >= 0 && index < tracks.size()) {
tracks.erase(tracks.begin() + index);
}
}
std::vector<Track>& DAW::getTracks() {
return tracks;
}
void DAW::loadAudio(const std::string& filePath, Track& track) {
SF_INFO sfInfo;
SNDFILE* sndFile = sf_open(filePath.c_str(), SFM_READ, &sfInfo);
if (!sndFile) {
throw std::runtime_error("Failed to open audio file: " + filePath);
}
track.fileName = filePath;
track.sampleRate = sfInfo.samplerate;
track.channels = sfInfo.channels;
track.duration = static_cast<double>(sfInfo.frames) / sfInfo.samplerate;
size_t totalFrames = sfInfo.frames * sfInfo.channels;
track.audioData.resize(totalFrames);
sf_read_float(sndFile, track.audioData.data(), totalFrames);
sf_close(sndFile);
}
void DAW::play() {
if (tracks.empty() || playing) return;
playing = true;
Pa_Initialize();
auto& track = tracks[0];
PaStream* stream;
Pa_OpenDefaultStream(&stream, 0, track.channels, paFloat32, track.sampleRate,
256, audioCallback, &track);
Pa_StartStream(stream);
std::thread playbackThread([stream]() {
while (Pa_IsStreamActive(stream) == 1) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
Pa_CloseStream(stream);
Pa_Terminate();
});
playbackThread.detach();
}
static int mixedAudioCallback(const void* inputBuffer, void* outputBuffer,
unsigned long framesPerBuffer, const PaStreamCallbackTimeInfo* timeInfo,
PaStreamCallbackFlags statusFlags, void* userData) {
static size_t position = 0;
auto* mixedAudio = static_cast<std::vector<float>*>(userData);
auto* out = static_cast<float*>(outputBuffer);
size_t toCopy = std::min<size_t>(framesPerBuffer * 2, mixedAudio->size() - position);
std::copy(mixedAudio->begin() + position, mixedAudio->begin() + position + toCopy, out);
position += toCopy;
if (position >= mixedAudio->size()) {
position = 0;
return paComplete;
}
return paContinue;
}
void DAW::playAll() {
if (tracks.empty() || playing) return;
playing = true;
Pa_Initialize();
size_t maxSamples = 0;
for (const auto& track : tracks) {
maxSamples = std::max(maxSamples, track.audioData.size());
}
std::vector<float> mixedAudio(maxSamples, 0.0f);
for (const auto& track : tracks) {
for (size_t i = 0; i < track.audioData.size(); ++i) {
mixedAudio[i] += track.audioData[i] / tracks.size();
}
}
PaStream* stream;
Pa_OpenDefaultStream(&stream, 0, 2, paFloat32, tracks[0].sampleRate, 256,
mixedAudioCallback, &mixedAudio);
Pa_StartStream(stream);
std::thread playbackThread([stream]() {
while (Pa_IsStreamActive(stream) == 1) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
}
Pa_CloseStream(stream);
Pa_Terminate();
});
playbackThread.detach();
}
void DAW::stop() {
playing = false;
Pa_Terminate();
}
bool DAW::isPlaying() const {
return playing;
}
+33
View File
@@ -0,0 +1,33 @@
#ifndef DAW_H
#define DAW_H
#include <vector>
#include <string>
struct Track {
std::string fileName;
int sampleRate;
int channels;
double duration;
std::vector<float> audioData;
};
class DAW {
public:
void addTrack(const std::string& filePath);
void removeTrack(int index);
std::vector<Track>& getTracks();
void play();
void playAll();
void stop();
bool isPlaying() const;
private:
std::vector<Track> tracks;
bool playing = false;
void loadAudio(const std::string& filePath, Track& track);
};
#endif
+85
View File
@@ -0,0 +1,85 @@
#include "gui.h"
#include "trackeditor.h"
enum {
ID_PLAY_PAUSE = 1
};
BEGIN_EVENT_TABLE(GUI, wxFrame)
EVT_BUTTON(ID_PLAY_PAUSE, GUI::OnPlayPause)
EVT_KEY_DOWN(GUI::OnKeyDown)
END_EVENT_TABLE()
GUI::GUI(const wxString& title)
: wxFrame(nullptr, wxID_ANY, title, wxDefaultPosition, wxSize(600, 400)) {
auto* panel = new wxPanel(this, wxID_ANY);
auto* vbox = new wxBoxSizer(wxVERTICAL);
trackList = new wxListBox(panel, wxID_ANY);
vbox->Add(trackList, 1, wxEXPAND | wxALL, 10);
auto* hbox = new wxBoxSizer(wxHORIZONTAL);
auto* addBtn = new wxButton(panel, wxID_ANY, wxT("Add Track"));
auto* removeBtn = new wxButton(panel, wxID_ANY, wxT("Remove Track"));
auto* playPauseBtn = new wxButton(panel, ID_PLAY_PAUSE, wxT("Play/Pause"));
auto* trackEditorBtn = new wxButton(panel, wxID_ANY, "Open Track Editor");
hbox->Add(trackEditorBtn, 1, wxEXPAND | wxALL, 5);
hbox->Add(addBtn, 1, wxEXPAND | wxALL, 5);
hbox->Add(removeBtn, 1, wxEXPAND | wxALL, 5);
hbox->Add(playPauseBtn, 1, wxEXPAND | wxALL, 5);
vbox->Add(hbox, 0, wxALIGN_CENTER);
panel->SetSizer(vbox);
Connect(addBtn->GetId(), wxEVT_BUTTON, wxCommandEventHandler(GUI::OnAddTrack));
Connect(removeBtn->GetId(), wxEVT_BUTTON, wxCommandEventHandler(GUI::OnRemoveTrack));
trackEditorBtn->Bind(wxEVT_BUTTON, &GUI::OnOpenTrackEditor, this);
}
void GUI::OnOpenTrackEditor(wxCommandEvent& event) {
auto* editor = new TrackEditor(&daw);
editor->Show(true);
}
void GUI::OnAddTrack(wxCommandEvent& event) {
wxFileDialog openFileDialog(this, wxT("Select Audio File"), "", "",
"Audio Files (*.wav;*.mp3;*.flac)|*.wav;*.mp3;*.flac",
wxFD_OPEN | wxFD_FILE_MUST_EXIST);
if (openFileDialog.ShowModal() == wxID_CANCEL) return;
daw.addTrack(openFileDialog.GetPath().ToStdString());
UpdateTrackList();
}
void GUI::OnRemoveTrack(wxCommandEvent& event) {
int selection = trackList->GetSelection();
if (selection != wxNOT_FOUND) {
daw.removeTrack(selection);
UpdateTrackList();
}
}
void GUI::OnPlayPause(wxCommandEvent& event) {
if (daw.isPlaying()) {
daw.stop();
}
else {
daw.play();
}
}
void GUI::OnKeyDown(wxKeyEvent& event) {
if (event.GetKeyCode() == WXK_SPACE) {
wxCommandEvent dummyEvent;
OnPlayPause(dummyEvent);
}
event.Skip();
}
void GUI::UpdateTrackList() {
trackList->Clear();
for (const auto& track : daw.getTracks()) {
trackList->Append(wxString::FromUTF8(track.fileName));
}
}
+27
View File
@@ -0,0 +1,27 @@
#ifndef GUI_H
#define GUI_H
#include <wx/wx.h>
#include <wx/dnd.h>
#include "daw.h"
class GUI : public wxFrame {
public:
GUI(const wxString& title);
private:
DAW daw;
wxListBox* trackList;
void OnAddTrack(wxCommandEvent& event);
void OnRemoveTrack(wxCommandEvent& event);
void OnPlayPause(wxCommandEvent& event);
void OnOpenTrackEditor(wxCommandEvent& event);
void OnKeyDown(wxKeyEvent& event);
void UpdateTrackList();
DECLARE_EVENT_TABLE()
};
#endif
+13
View File
@@ -0,0 +1,13 @@
#include <wx/wx.h>
#include "gui.h"
class ApfelDAWApp : public wxApp {
public:
virtual bool OnInit() {
GUI* gui = new GUI("Apfel DAW");
gui->Show(true);
return true;
}
};
wxIMPLEMENT_APP(ApfelDAWApp);
+50
View File
@@ -0,0 +1,50 @@
#include "trackeditor.h"
FileDropTarget::FileDropTarget(wxListBox* listBox, DAW* daw)
: trackList(listBox), daw(daw) {}
bool FileDropTarget::OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& files) {
for (const auto& file : files) {
try {
daw->addTrack(file.ToStdString());
trackList->Append(file);
}
catch (const std::exception& e) {
wxMessageBox(e.what(), "Error", wxICON_ERROR);
}
}
return true;
}
TrackEditor::TrackEditor(DAW* daw)
: wxFrame(nullptr, wxID_ANY, "Track Editor", wxDefaultPosition, wxSize(600, 400)), daw(daw) {
auto* panel = new wxPanel(this, wxID_ANY);
auto* vbox = new wxBoxSizer(wxVERTICAL);
trackList = new wxListBox(panel, wxID_ANY);
auto* dropTarget = new FileDropTarget(trackList, daw);
trackList->SetDropTarget(dropTarget);
vbox->Add(trackList, 1, wxEXPAND | wxALL, 10);
auto* hbox = new wxBoxSizer(wxHORIZONTAL);
auto* playBtn = new wxButton(panel, wxID_ANY, "Play All");
auto* stopBtn = new wxButton(panel, wxID_ANY, "Stop");
hbox->Add(playBtn, 1, wxEXPAND | wxALL, 5);
hbox->Add(stopBtn, 1, wxEXPAND | wxALL, 5);
vbox->Add(hbox, 0, wxALIGN_CENTER);
panel->SetSizer(vbox);
Connect(playBtn->GetId(), wxEVT_BUTTON, wxCommandEventHandler(TrackEditor::OnPlay));
Connect(stopBtn->GetId(), wxEVT_BUTTON, wxCommandEventHandler(TrackEditor::OnStop));
}
void TrackEditor::OnPlay(wxCommandEvent& event) {
daw->playAll();
}
void TrackEditor::OnStop(wxCommandEvent& event) {
daw->stop();
}
+30
View File
@@ -0,0 +1,30 @@
#ifndef TRACKEDITOR_H
#define TRACKEDITOR_H
#include <wx/wx.h>
#include <wx/dnd.h>
#include "daw.h"
class FileDropTarget : public wxFileDropTarget {
public:
FileDropTarget(wxListBox* listBox, DAW* daw);
bool OnDropFiles(wxCoord x, wxCoord y, const wxArrayString& files) override;
private:
wxListBox* trackList;
DAW* daw;
};
class TrackEditor : public wxFrame {
public:
TrackEditor(DAW* daw);
private:
DAW* daw;
wxListBox* trackList;
void OnPlay(wxCommandEvent& event);
void OnStop(wxCommandEvent& event);
};
#endif