2012-08-09 73 views

回答

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網址:

  • 驗證令牌(組oauth_token)
  • 歌曲名稱(軌跡[標題])
  • 的文件(軌道[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)

+0

不錯!有用! – 2012-08-09 22:14:18

+0

哪裏可以得到這個oauth_token?我在聲音雲上添加了一個應用程序,但不知道生成oauth_token的熱。 – 2012-11-03 09:39:50

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) { 
       ... 
      } 
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","[email protected]"), 
       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);     
     } 
    } 
} 
+0

ISoundPlatformService在哪裏定義? – Howiecamp 2015-12-29 22:28:30

+0

ISoundPlatformService接口只包含方法的定義。這是一個自定義界面,我的意思是,界面不在Sound Cloud dll中。我定義了使用IoC的接口。 – 2016-01-04 08:04:45

+0

噢,好的。您可能希望從代碼中刪除該代碼,以簡化代碼並避免讓人疑惑。 – Howiecamp 2016-01-06 21:34:14