我正在尝试使用souncloud API和javascript将歌曲上传到soundcloud。但我似乎无法做到这一点。这是我的javascript
function ADDTRACK() {
var test = document.getElementById('SongTrack').files[0];
SC.get("http://api.soundcloud.com/users/redstr/tracks.json?client_id=3200814596a029b47877e63edfe6066c", {
limit: 1
}, function(tracks) {
SC.POST({
tracks: {
description: 'This track was recorded in Berlin',
asset_data: '@' + test
}
});
});
}
这是我的HTML上传
<input type="file" id ="SongTrack" name="pic" accept="audio/*" />
<button type="button" onclick="ADDTRACK()" />Add TRACK</button>
我没有错误,所以有人能指出我做错了吗?
答案 0 :(得分:2)
来自:http://developers.soundcloud.com/docs/api/guide#uploading
// the JavaScript SDK does not by itself have access
// to the filesystem, so instead this example records
// some audio in the browser and uploads it.
SC.connect(function() {
SC.record({
start: function() {
window.setTimeout(function() {
SC.recordStop();
SC.recordUpload({
track: { title: 'This is my sound' }
});
}, 5000);
}
}
});
因此,您无法使用javascript直接上传曲目。
答案 1 :(得分:1)
我最终也希望通过Javascript SDK上传音频文件,因此我对PHP和JS SDK进行了反向设计以使其正常工作。
首先,您应该确保Javascript SDK正常运行。我们只将它用于身份验证令牌(使用未记录的方法)。除了令牌之外,其余部分都是使用$.ajax
和FormData
对象手动处理的。
HTML:
<script src="//cdn.jsdelivr.net/jquery/1.8.3/jquery-1.8.3.min.js"></script>
<script src="//connect.soundcloud.com/sdk.js"></script>
<button id="login">log in</button>
<form>
<label>Title: <input name="title" disabled /></label><br>
<label>File: <input name="file" type="file" accept="audio/*" disabled /></label><br>
<button type="submit" disabled >Submit</button>
</form>
使用Javascript:
SC.initialize({
client_id: "INSERT_CLIENT_ID",
redirect_uri: "INSERT_REDIRECT_URI"
});
$("#login").click(function(){
SC.connect(function(){
$('form input,form button').removeAttr('disabled');
});
});
$('form').submit(function(e) {
var fd = new FormData();
fd.append('oauth_token', SC.accessToken());
fd.append('format','json');
fd.append("track[title]", $(this).find('input[name=title]').val());
fd.append("track[asset_data]", $(this).find('input[name=file]').prop('files')[0]);
$.ajax({
url: 'https://api.soundcloud.com/v1/tracks',
type: 'POST',
data: fd,
processData: false,
contentType: false,
xhr: function() {
var xhr = $.ajaxSettings.xhr();
xhr.upload.onprogress = function(e) {
if(e.lengthComputable) {
var percent = Math.floor((e.loaded / e.total) * 100);
console.log(percent + '% uploaded');
}
};
return xhr;
}
}).done(function(e) {
console.log('Upload Complete!');
console.dir(e); // This is the JSON object of the resulting track
});
e.preventDefault();
});