Search code examples
c#.netaudiosoundcloud

Connecting to and uploading tracks with Soundcloud API using C# .NET


I'm trying to upload an audio track to the Soundcloud.com using C#.NET, but there aren't any resources for .NET anywhere. Could someone post a link or an example of how to upload an audio file to my Soundcloud.com account using .NET?


Solution

  • To upload an audio using soundcloud's REST API you need to take care of HTTP POST related issues (RFC 1867). In general, ASP.NET does not support sending of multiple files/values using POST, so I suggest you to use Krystalware library: http://aspnetupload.com/Upload-File-POST-HttpWebRequest-WebClient-RFC-1867.aspx

    After that you need to send proper form fields to the https://api.soundcloud.com/tracks url:

    • Auth token (oauth_token)
    • Track Title (track[title])
    • The file (track[asset_data])

    Sample code:

    using Krystalware.UploadHelper;
    ...
    
    System.Net.ServicePointManager.Expect100Continue = false;
    var request = WebRequest.Create("https://api.soundcloud.com/tracks") as HttpWebRequest;
    //some default headers
    request.Accept = "*/*";
    request.Headers.Add("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.3");
    request.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
    request.Headers.Add("Accept-Language", "en-US,en;q=0.8,ru;q=0.6");
    
    //file array
    var files = new UploadFile[] { 
        new UploadFile(Server.MapPath("Downloads//0.mp3"), "track[asset_data]", "application/octet-stream") 
    };
    //other form data
    var form = new NameValueCollection();
    form.Add("track[title]", "Some title");
    form.Add("track[sharing]", "private");
    form.Add("oauth_token", this.Token);
    form.Add("format", "json");
    
    form.Add("Filename", "0.mp3");
    form.Add("Upload", "Submit Query");
    try
    {
        using (var response = HttpUploadHelper.Upload(request, files, form))
        {
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                lblInfo.Text = reader.ReadToEnd();
            }
        }
    }
    catch (Exception ex)
    {
        lblInfo.Text = ex.ToString();
    }
    

    The example code allows you to upload an audio file from the server (notice the Server.MapPath method to form path to the file) and to get a response in json format (reader.ReadToEnd)