0
votes

I'm using libspotify to retrieve music to play with some audio library. The spotify music should be in raw 16bit, 44100hz, stereo LPCM. I have been trying to play the music with NAudio, but unfortunatly it's not in stereo.

From spotify docs: Samples are delivered as integers, see sp_audioformat. One frame consists of the same number of samples as there are channels. I.e. interleaving is on the sample level.

The following code plays a song in mono from a file. The file is a copy of the spotify music data.

Can someone guide my towards a stereo solution. It could be any audio library preferebly in .NET.

using (var waveOutDevice = new WaveOut())
{

    using (var pcmStream = new FileStream(PcmFile, FileMode.Open))
    {
        WaveStream waveStream = null;
        try
        {
            const int sampleRate = 44100;
            const int channels = 2;
            var waveFormat = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, sampleRate * channels, 1, sampleRate*2*channels, channels, 16);
            waveStream = new RawSourceWaveStream(pcmStream, waveFormat);

            waveOutDevice.Init(waveStream);
            waveOutDevice.Play();

            Thread.Sleep(5000); //Listen to 5 secs of music

        }
        finally
        {
            waveOutDevice.Stop();
            if (waveStream != null) waveStream.Close();
        }
    }
}

Signatur for CreateCustomFormat is public static NAudio.Wave.WaveFormat CreateCustomFormat(NAudio.Wave.WaveFormatEncoding tag, int sampleRate, int channels, int averageBytesPerSecond, int blockAlign, int bitsPerSample)

2

2 Answers

1
votes

This is stereo:

const int bitsPerSample = 16;
int blockAlign = (channels * (bitsPerSample / 8));
int averageBytesPerSecond = sampleRate * blockAlign;
var waveFormat = WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, sampleRate, channels, averageBytesPerSecond, blockAlign, bitsPerSample);
0
votes

Maybe you're passing wrong values to CreateCustomFormat. Try with following:

WaveFormat.CreateCustomFormat(WaveFormatEncoding.Pcm, sampleRate, channels, sampleRate*channels, 1, 8);