title: waveOutWrite buffers are never returned to application
body: <p>I have a problem with Microsoft's WaveOut API:</p>
  
  <p>edit1: Added Link to sample project:
  edit2: removed link, its not representative of the issue</p>
  
  <p>After playing some audio, when I want to terminate a given playback stream, I call the function:</p>
  
  <pre><code>waveOutClose(hWaveOut_);
  </code></pre>
  
  <p>However, even after waveOutClose() is called, sometimes the library will still access memory previously passed to it by waveOutWrite(), causing an invalid memory access.</p>
  
  <p>I then tried to ensure all the buffers are marked as done before freeing the buffer:</p>
  
  <pre><code>PcmPlayback::~PcmPlayback()
  {
  if(hWaveOut_ == nullptr)
      return;
  
      waveOutReset(hWaveOut_); // infinite-loops, never returns
  
  for(auto it = buffers_.begin(); it != buffers_.end(); ++it)
      waveOutUnprepareHeader(hWaveOut_, &amp;it-&gt;wavehdr_, sizeof(WAVEHDR));
  
  while( buffers_.empty() == false ) // infinite loops
      removeCompletedBuffers();
  
  waveOutClose(hWaveOut_);
  
  //Unhandled exception at 0x75629E80 (msvcrt.dll) in app.exe: 
  // 0xC0000005: Access violation reading location 0xFEEEFEEE.
  }
  
  void PcmPlayback::removeCompletedBuffers()
  {
  for(auto it = buffers_.begin(); it != buffers_.end();)
  {
      if( it-&gt;wavehdr_.dwFlags &amp; WHDR_DONE )
      {
          waveOutUnprepareHeader(hWaveOut_, &amp;it-&gt;wavehdr_, sizeof(WAVEHDR));
          it = buffers_.erase(it);
      }
      else
          ++it;
  }
  }
  </code></pre>
  
  <p>However, this situation never happens - the buffer never becomes empty. There will be 4-5 blocks remaining with wavehdr_.dwFlags == 18 (I believe this means the blocks are still marked as in playback)</p>
  
  <p>How can I resolve this issue?</p>
  
  <p>@ Martin Schlott ("Can you provide the loop where you write the buffer to waveOutWrite?")
  Its not quite a loop, instead I have a function that is called whenever I receive an audio packet over the network:</p>
  
  <pre><code>void PcmPlayback::addData(const std::vector&lt;short&gt; &amp;rhs)
  {
  removeCompletedBuffers();
  
  if(rhs.empty())
      return;
  
  // add new data
  buffers_.push_back(Buffer());
  
  Buffer &amp; buffer = buffers_.back();
  buffer.data_ = rhs;
  ZeroMemory(&amp;buffers_.back().wavehdr_, sizeof(WAVEHDR));
  buffer.wavehdr_.dwBufferLength = buffer.data_.size() * sizeof(short);
  buffer.wavehdr_.lpData = (char *)(buffer.data_.data());
  waveOutPrepareHeader(hWaveOut_, &amp;buffer.wavehdr_, sizeof(WAVEHDR)); // prepare block for playback
  waveOutWrite(hWaveOut_, &amp;buffer.wavehdr_, sizeof(WAVEHDR));
  }
  </code></pre>