Search code examples
c#naudio

How to play audio samples without writing it into to a file?


I get audio samples (as float array) from another method and I want to play this float array without writing any files to disk.

For this example I get samples from audio file:

var file = new AudioFileReader(stereoFile);

int startPos = 0;
int endPos = 138890;

var sampleArray = new float[endPos - startPos];

file.Read(sampleArray, startPos, sampleArray.Length);

How can I play sampleArray?


Solution

  • I find next solution and it work for me:

            var file = new AudioFileReader(stereoFile);
    
            WaveFormat waveFormat = file.WaveFormat;
    
            int startPos = 2403;
            int endPos = 41265;
    
            if (startPos % 2 != 0)
            {
                startPos += 1;
            }
    
            if (endPos % 2 != 0)
            {
                endPos += 1;
            }
    
            if (waveFormat.Channels == 2)
            {
                startPos *= 2;
                endPos *= 2;
            }
    
            var allSamples = new float[file.Length / (file.WaveFormat.BitsPerSample / 8)];
    
            file.Read(allSamples, 0, allSamples.Length);
    
            Span<float> samplesSpan = allSamples;
            Span<float> trackSpan = samplesSpan.Slice(startPos, endPos - startPos);
    

    ^ upper code to take correct samples for tests. code below - my solution

            MemoryStream ms = new MemoryStream();
            IgnoreDisposeStream ids = new IgnoreDisposeStream(ms);
    
            using (WaveFileWriter waveFileWriter = new WaveFileWriter(ids, waveFormat))
            {
                waveFileWriter.WriteSamples(trackSpan.ToArray(), 0, endPos-startPos);
            }
    
    
            ms.Position = 0;
            WaveStream waveStream = new WaveFileReader(ms);
            WaveOutEvent waveOutEvent = new WaveOutEvent();
            waveOutEvent.Init(waveStream);
            waveOutEvent.Play();