7

我正在尝试使用 C#.NET 将音轨上传到 Soundcloud.com,但在任何地方都没有任何 .NET 资源。有人可以发布如何使用 .NET 将音频文件上传到我的 Soundcloud.com 帐户的链接或示例吗?

谢谢你,阿曼

4

3 回答 3

7

要使用 soundcloud 的 REST API 上传音频,您需要处理与 HTTP POST 相关的问题 (RFC 1867)。一般来说,ASP.NET 不支持使用 POST 发送多个文件/值,所以我建议你使用 Krystalware 库:http ://aspnetupload.com/Upload-File-POST-HttpWebRequest-WebClient-RFC-1867.aspx

之后,您需要将正确的表单字段发送到https://api.soundcloud.com/tracks url:

  • 身份验证令牌 (oauth_token)
  • 曲目标题(曲目[标题])
  • 文件 (track[asset_data])

示例代码:

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();
}

示例代码允许您从服务器上传音频文件(注意 Server.MapPath 方法来形成文件的路径)并获得 json 格式的响应(reader.ReadToEnd)

于 2012-08-09T21:58:56.503 回答
4

这是通过 SoundCloud API 上传曲目的代码片段 =>

        using (HttpClient httpClient = new HttpClient()) {
            httpClient.DefaultRequestHeaders.ConnectionClose = true;
            httpClient.DefaultRequestHeaders.UserAgent.Add(new ProductInfoHeaderValue("MySoundCloudClient", "1.0"));
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", "MY_AUTH_TOKEN");
            ByteArrayContent titleContent = new ByteArrayContent(Encoding.UTF8.GetBytes("my title"));
            ByteArrayContent sharingContent = new ByteArrayContent(Encoding.UTF8.GetBytes("private"));
            ByteArrayContent byteArrayContent = new ByteArrayContent(File.ReadAllBytes("MYFILENAME"));
            byteArrayContent.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            MultipartFormDataContent content = new MultipartFormDataContent();
            content.Add(titleContent, "track[title]");
            content.Add(sharingContent, "track[sharing]");
            content.Add(byteArrayContent, "track[asset_data]", "MYFILENAME");
            HttpResponseMessage message = await httpClient.PostAsync(new Uri("https://api.soundcloud.com/tracks"), content);

            if (message.IsSuccessStatusCode) {
                ...
            }
于 2013-10-11T12:50:13.303 回答
2

这是另一种使用 C# 获取非过期令牌并将音轨上传到 SoundCloud 的方法:

public class SoundCloudService : ISoundPlatformService
{
    public SoundCloudService()
    {
        Errors=new List<string>();
    }

    private const string baseAddress = "https://api.soundcloud.com/";

    public IList<string> Errors { get; set; }

    public async Task<string> GetNonExpiringTokenAsync()
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress = new Uri(baseAddress);
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair<string, string>("client_id","xxxxxx"),
                new KeyValuePair<string, string>("client_secret","xxxxxx"),
                new KeyValuePair<string, string>("grant_type","password"),
                new KeyValuePair<string, string>("username","xx@xx.com"),
                new KeyValuePair<string, string>("password","xxxxx"),
                new KeyValuePair<string, string>("scope","non-expiring")
            });

            var response = await client.PostAsync("oauth2/token", content);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                dynamic data = JsonConvert.DeserializeObject(await response.Content.ReadAsStringAsync());
                return data.access_token;
            }

            Errors.Add(string.Format("{0} {1}", response.StatusCode, response.ReasonPhrase));

            return null;
        }
    }        

    public async Task UploadTrackAsync(string filePath)
    {
        using (var client = new HttpClient())
        {
            client.BaseAddress=new Uri(baseAddress);

            var form = new MultipartFormDataContent(Guid.NewGuid().ToString());

            var contentTitle = new StringContent("Test");
            contentTitle.Headers.ContentType = null;
            form.Add(contentTitle, "track[title]");

            var contentSharing = new StringContent("private");
            contentSharing.Headers.ContentType = null;
            form.Add(contentSharing, "track[sharing]");

            var contentToken = new StringContent("xxxxx");
            contentToken.Headers.ContentType = null;
            form.Add(contentToken, "[oauth_token]");

            var contentFormat = new StringContent("json");
            contentFormat.Headers.ContentType = null;
            form.Add(contentFormat, "[format]");

            var contentFilename = new StringContent("test.mp3");
            contentFilename.Headers.ContentType = null;
            form.Add(contentFilename, "[Filename]");

            var contentUpload = new StringContent("Submit Query");
            contentUpload.Headers.ContentType = null;                                
            form.Add(contentUpload, "[Upload]");

            var contentTags = new StringContent("Test");
            contentTags.Headers.ContentType = null;
            form.Add(contentTags, "track[tag_list]");

            var bytes = File.ReadAllBytes(filePath);                
            var contentFile = new ByteArrayContent(bytes, 0, bytes.Count());                
            contentFile.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            form.Add(contentFile, "track[asset_data]", "test.mp3");

            var response = await client.PostAsync("tracks", form);                
        }
    }
}
于 2015-06-30T11:50:31.707 回答