Luis Lavieri
Luis Lavieri

Reputation: 4129

Streaming audio using libspotifydotnet (Spotify - libspotify)

After checking out this, this, and this post, I understand that I have to stream audio using something like NAudio and also that playing a song is done by:

libspotify.sp_session_player_load(_sessionPtr, trackPtr);
libspotify.sp_session_player_play(_sessionPtr, true);

Now, if I understood correctly, I am receiving the stream as raw PCM data. How can I access that data?

According to the documentation, I see that that I have to populate libspotify.sp_audioformat

How do I do this exactly? and from where?

I was checking out this project (Jamcast), and they do something like:

libspotify.sp_audioformat format = (libspotify.sp_audioformat)Marshal.PtrToStructure(formatPtr, typeof(libspotify.sp_audioformat));

Could someone point me in the right direction? I am completely lost on how to retrieve the stream

Upvotes: 1

Views: 1649

Answers (1)

Luis Lavieri
Luis Lavieri

Reputation: 4129

At the end, I followed this, and this question. They helped me out a lot.

I had to do something like this:

public static libspotify.sp_error LoadPlayer(IntPtr trackPtr)
{
    bufferedWaveProvider = new BufferedWaveProvider(new WaveFormat());
    bufferedWaveProvider.BufferDuration = TimeSpan.FromSeconds(120);

    return libspotify.sp_session_player_load(_sessionPtr, trackPtr);
}

public static void Play()
{
    libspotify.sp_session_player_play(_sessionPtr, true);

    IWavePlayer waveOutDevice = new WaveOut();
    waveOutDevice.Init(bufferedWaveProvider);
    waveOutDevice.Play();
    while (waveOutDevice.PlaybackState == PlaybackState.Playing)
    {
        Thread.Sleep(100);
    }   
}

private static int music_delivery(IntPtr sessionPtr, IntPtr formatPtr, IntPtr framesPtr, int num_frame)
{
    if (num_frame == 0)
        return 0;

    libspotify.sp_audioformat format = (libspotify.sp_audioformat)Marshal.PtrToStructure(formatPtr, typeof(libspotify.sp_audioformat));
    byte[] buffer = new byte[num_frame * sizeof(Int16) * format.channels];
    Marshal.Copy(framesPtr, buffer, 0, buffer.Length);

    bufferedWaveProvider.AddSamples(buffer, 0, num_frame * sizeof(Int16) * format.channels);

    if (Session.OnAudioDataArrived != null)            
        Session.OnAudioDataArrived(buffer);

    return num_frame;

}

Upvotes: 1

Related Questions