<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Harry Ashikian on Medium]]></title>
        <description><![CDATA[Stories by Harry Ashikian on Medium]]></description>
        <link>https://medium.com/@harry.ashikian?source=rss-fe4e2cb15c4f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*6wDydNnAGXCdFolM</url>
            <title>Stories by Harry Ashikian on Medium</title>
            <link>https://medium.com/@harry.ashikian?source=rss-fe4e2cb15c4f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 16:06:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@harry.ashikian/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[3D Audio System in C++]]></title>
            <link>https://medium.com/@harry.ashikian/3d-audio-system-in-c-38aaa827ee03?source=rss-fe4e2cb15c4f------2</link>
            <guid isPermaLink="false">https://medium.com/p/38aaa827ee03</guid>
            <category><![CDATA[audio-programming]]></category>
            <category><![CDATA[c-plus-plus-language]]></category>
            <category><![CDATA[from-scratch]]></category>
            <category><![CDATA[spatial-audio]]></category>
            <category><![CDATA[3d-audio]]></category>
            <dc:creator><![CDATA[Harry Ashikian]]></dc:creator>
            <pubDate>Fri, 24 Jan 2025 02:50:21 GMT</pubDate>
            <atom:updated>2025-01-24T11:24:51.424Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6aCQM0jlUTzLjTYKmmiNRA.jpeg" /></figure><h4>My journey of creating a 3D audio system from scratch.</h4><p>In this blog, I will be talking about the implementation of my custom 3D audio system from scratch in C++. The goal was to create a general-purpose tool that could be easily integrated into future games, delivering immersive 3D sound with features like spatialization, occlusion, reverb, etc. Below, I’ll explain each major step of the process and how it is implemented.</p><h4>Creating the header:</h4><p>The first step was to define a structure for the WAV file header. The header provides information, like the audio format, sample rate, bits per sample and number of channels, which will be needed for the implementation.</p><pre>struct WavFile {<br>    char chunkID[4];       // &quot;RIFF&quot;<br>    uint32_t chunkSize;    // File size<br>    char format[4];        // &quot;WAVE&quot;<br>    char subChunk1ID[4];   // &quot;fmt &quot;<br>    uint32_t subChunk1Size; // Size of the fmt chunk<br>    uint16_t audioFormat;   // PCM = 1<br>    uint16_t numChannels;   // Number of channels<br>    uint32_t sampleRate;    // Sampling rate<br>    uint32_t byteRate;      // Byte rate<br>    uint16_t blockAlign;    // Block alignment<br>    uint16_t bitsPerSample; // Bits per sample<br>    char subChunk2ID[4];    // &quot;data&quot;<br>    uint32_t subChunk2Size; // Size of the data chunk<br>};</pre><p>A detailed explanation of the WAVE data format can be found <a href="http://soundfile.sapp.org/doc/WaveFormat/">here</a>.</p><h4>Why the Wave audio format?</h4><p>For this project, I chose the WAV file format over alternatives like MP3. Here’s why:</p><ul><li>Unlike MP3, WAV files are uncompressed and keep their original quality.</li><li>WAV files are highly editable. Since they are uncompressed, the data can be changed without risking further quality loss.</li><li>The WAV format is well-structured and easy to parse, making it suitable for development and as in my case learning purposes.</li></ul><h4>Loading the WAV file:</h4><p>With the header structure ready, the next step was to create a WAV file loader. This function reads an audio file, validates its format, and extracts the audio data into the header.</p><p>The method begins by opening the wave file in binary mode:</p><pre>ifstream file(filePath, std::ios::binary);</pre><p>72 byte wave file opened in a hexadecimal format</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/673/1*v8LZ4s2q34DtDZgykNVrHg.gif" /></figure><p>Then header is populated with the audio data. After which we can verify if the audio format is correct. The size of the WAV header is used to accurately assign its parameters.</p><pre>file.read(reinterpret_cast&lt;char*&gt;(&amp;wav), sizeof(WavFile));<br>if (strncmp(wav.chunkID, &quot;RIFF&quot;, 4) != 0 || strncmp(wav.format, &quot;WAVE&quot;, 4) != 0) {<br>    std::cerr &lt;&lt; &quot;Error: Invalid WAV file format. Supported format: RIFF/WAVE.&quot; &lt;&lt; std::endl;<br>    return;<br>}</pre><p>The subChunk2Size shows the size of the audio data. Using this information, the method gets the number of samples and resizes our vector to hold the samples. The audio data is then read directly into the vector. The vector is of type int16_t due to the standard wave format of 16 PCM.</p><pre>size_t sampleCount = wav.subChunk2Size / sizeof(int16_t);<br><br>wavData.resize(sampleCount);<br>file.read(reinterpret_cast&lt;char*&gt;(wavData.data()), wav.subChunk2Size);</pre><h4>Mono to Stereo conversion:</h4><p>To achieve 3D audio, some wave files need to be converted from mono to stereo, so we can modify both audio channels. To do this, we need to first resize our data buffer to accommodate twice the number of samples.</p><p>Then a loop iterates through all the mono samples, duplicating them to format a pair of left and right channel values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w1Frllh16C2UcPABjXJgWA.png" /></figure><pre>int16_t monoSample = wavData[i];<br>int16_t leftChannelSample = monoSample;<br>int16_t rightChannelSample = monoSample;<br>stereoData[i] = { leftChannelSample, rightChannelSample };</pre><p>After that we access the audio’s data through the header to modify the number of channels. The byte rate and block align need to be recalculated as well.</p><p>When all of this is done, the samples are stored back into the data buffer.</p><h4>Spatialization with Stereo Panning:</h4><p>Spatialization is the process of simulating how sound behaves in a 3D environment. It allows the listener to determine the direction from which the audio source comes from.</p><p>For this I used a standard stereo panning algorithm. By calculating the position and rotation of the listener relative to the one of the audio source, the method adjusts the volume of the left and right channels to create the illusion of directionality.</p><pre>const vec3 directionToListener = sourcePosition - firstPosition;<br><br>vec4 localDirection = inverse(rotationMatrix) * vec4(directionToListener, 0.0f);<br><br>const float angle = atan2(localDirection.z, localDirection.x);<br>const float cosTheta = cos(angle);<br><br>float spatialLeftFactor = 1.0f - cosTheta;<br>float spatialRightFactor = 1.0f + cosTheta;</pre><p>Here is an example of the stereo panning in action with two audio sources.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FM7JyfXs25dc%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DM7JyfXs25dc&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FM7JyfXs25dc%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/14864a10837dfd024fe16433bd0ed155/href">https://medium.com/media/14864a10837dfd024fe16433bd0ed155/href</a></iframe><h4>Distance Attenuation:</h4><p>To simulate realistic behavior in audio, we use distance attenuation to reduce the intensity of sound as the listener moves further away from the source. This effect is made by using the <strong>inverse square law</strong>, which states that the intensity of a sound wave decreases in proportion to the square of the distance from the source.</p><pre>float attenuation = 1.0f / (1.0f + factor * distance * distance);</pre><h4>Occlusion with Ray Tracing:</h4><p>To make the audio more realistic, I added occlusion. This feature reduces the sound’s volume and applies a low pass filter if an obstacle blocks the line of sight between the audio source and the listener. For this to work I implemented a simple ray tracing algorithm which checks for collisions with objects in the game world.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*CD0zojT5YgvdNybc2ijLqw.gif" /></figure><p>Lowpass FIR filter:<br>The lowpass filter is a smoothing algorithm which is used to blend two audio samples, creating a muffled effect. This is achieved by computing the output from the current and previous inputs.</p><p>For this we need some variables</p><pre>const float alpha = 0.1f;<br>float previousLeft = 0.0f, previousRight = 0.0f;</pre><p>The alpha is used as a factor for how much smoothing is applied. Usually it has it’s own formula but for simplicity’s sake I used a hardcoded value. Previous left and right are used to store the previous audio samples which we will blend with the current ones, which creates the smoothing effect.</p><p>To calculate the FIR (finite impulse response) filter we do the following calculation:</p><pre>(sample * alpha) + (prev * (1.0 - alpha));</pre><p>Volume control:<br>Each object is assigned a predefined value that indicates how much sound it allows to pass through. Instead of focusing on the specific properties of materials like wood or metal, the system uses general categories — Low, Medium, and High. These categories determine the degree to which the incoming sound is reduced, simplifying the process while maintaining flexibility.</p><pre>switch (objectMat.passType)<br>{<br>case 0: //Low<br>    volumeReduction = 0.25f;<br>    break;<br>case 1: //Medium<br>    volumeReduction = 0.65f;<br>    break;<br>case 2: // High<br>    volumeReduction = 0.95f;<br>    break;<br>}</pre><p>Here is a video of using the occlusion effect</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FL_5d-RN4sBg%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DL_5d-RN4sBg&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FL_5d-RN4sBg%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/fdfe5dde01dd712e79b28c2391634dbf/href">https://medium.com/media/fdfe5dde01dd712e79b28c2391634dbf/href</a></iframe><h4>Reverb Zones:</h4><p>Reverb Zones are a predefined areas which apply a reverb/echo effect to the audio in order to simulate certain scenarios. For example, being inside a cave, corridor, lecture room, etc. This is achieved by creating delayed and decayed copies of the original audio signal.</p><p>The reverb zone is made so it always looks for objects of the Audioclass, making it suitable both for stationary and moving audio sources.</p><pre>for (bee::Audio* audio : bee::Audio::audioObjects)<br>{<br>    if (Triggered(audio-&gt;position, zonePosition, zoneScale))<br>    {<br>      //apply delay samples</pre><p>We create a temporary audio buffer which then we extend the length of based on the delayed samples or else the reverb will end with the original audio, we don’t want this when we apply it to short sound effects.</p><pre>size_t extendedSize = originalSize + delaySamples * 2;<br>tempoReverbData.resize(extendedSize, 0);</pre><p>We define a decay factor which reduces the intensity of the delay samples with each reflection.</p><pre>float decay = 0.3f;<br><br>tempoReverbData[delayedIndex] += (tempoReverbData[i] * decay); <br>https://youtu.be/Jhbd2XixS4A?si=_GiiP0XaPou9Re-n</pre><p>Example of the reverb zone in a class hall scenario:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FJhbd2XixS4A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DJhbd2XixS4A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FJhbd2XixS4A%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c76e52d4eb449966e17d516d6e6a573/href">https://medium.com/media/7c76e52d4eb449966e17d516d6e6a573/href</a></iframe><p>Another instance of the same approach can be seen in the <a href="https://docs.unity3d.com/400/Documentation/Components/class-AudioReverbZone.html">Unity Game Engine</a>.</p><h4>Conclusion:</h4><p>I’ve showcased the current features of my 3D Audio tool, and there is more planned for the future. I will first focus on performance improvements, improve some of the features in terms of complexity and finally turn the project into a fully-fledged third-party library, which can be easily included and used inside any project.</p><p>Thank you for taking the time to read my article! If you have any questions or would like to share your feedback, feel free to reach out to me at harry.ashikian@gmail.com.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lWmfhS7WqTQTm-X0WvF4cg.png" /></figure><h4>Sources:</h4><ul><li><a href="http://soundfile.sapp.org/doc/WaveFormat/">Microsoft WAVE soundfile format</a></li><li><a href="https://audiouniversityonline.com/inverse-square-law-of-sound/">Inverse Square Law of Sound: Simple Explanation</a></li><li><a href="https://www.audiokinetic.com/en/library/edge/?source=SDK&amp;id=soundengine_obsocc.html">Documentation | Audiokinetic</a></li><li><a href="https://stackoverflow.com/questions/5318989/reverb-algorithm">Reverb Algorithm</a></li><li><a href="https://amini-allight.org/post/game-audio-programming-tutorial-part-4">Game Audio Programming Tutorial: Part 4 - Sound Panning</a></li></ul><p>Lecture Hall from malkaviana (<a href="https://sketchfab.com/malkaviana">https://sketchfab.com/malkaviana</a>)</p><p>Title picture by <a href="https://unsplash.com/@cdx2?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">C D-X</a> on <a href="https://unsplash.com/photos/flatlay-photography-of-wireless-headphones-PDX_a_82obo?utm_content=creditCopyText&amp;utm_medium=referral&amp;utm_source=unsplash">Unsplash</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38aaa827ee03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>