Skip to content

Instantly share code, notes, and snippets.

@jmatsu
Created January 17, 2015 18:22
Show Gist options
  • Save jmatsu/9db7d3cab5552ce7c798 to your computer and use it in GitHub Desktop.
Save jmatsu/9db7d3cab5552ce7c798 to your computer and use it in GitHub Desktop.
Retrieving a audio from SoundCloud
import android.content.Context;
import com.soundcloud.api.ApiWrapper;
import com.soundcloud.api.Request;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.IOException;
import jp.maju.tweetdocker.R;
import jp.maju.tweetdocker.utils.Logger;
/**
* Created by jmatsu on 2014/10/21.
*/
public class RequestSoundCloudTask extends AsyncParallelTask<Void, Void, String> {
private static final String TAG = RequestSoundCloudTask.class.getSimpleName();
private final String mClientId;
private final String mClientSecretId;
private final String mRequestId;
private OnRequestSoundCloudListener mOnRequestSoundCloudListener;
public RequestSoundCloudTask(Context context, String request) {
mClientId = context.getString(R.string.sound_cloud_client_id);
mClientSecretId = context.getString(R.string.sound_cloud_client_secret);
mRequestId = request;
}
public RequestSoundCloudTask setOnRequestSoundCloudListener(OnRequestSoundCloudListener listener) {
mOnRequestSoundCloudListener = listener;
return this;
}
@Override
protected String doInBackground(Void... params) {
ApiWrapper wrapper = new ApiWrapper(mClientId,mClientSecretId, null, null);
try {
HttpResponse trackResp = wrapper.get(Request.to(mRequestId));
if(trackResp.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
JSONObject trackJSON = new JSONObject(EntityUtils.toString(trackResp.getEntity()));
if(trackJSON.getBoolean("streamable")) {
HttpResponse streamResp = wrapper.get(Request.to(mRequestId+"/stream"));
JSONObject streamJSON = new JSONObject(EntityUtils.toString(streamResp.getEntity()));
String streamUrl = streamJSON.getString("location");
Logger.i(TAG, streamUrl);
return streamUrl;
}
}
} catch (IOException e) {
Logger.e(TAG, "IOException", e);
}catch (ParseException e) {
Logger.e(TAG, "ParseException", e);
} catch (JSONException e) {
Logger.e(TAG, "JSONException", e);
}
return null;
}
@Override
protected void onPostExecute(String s) {
if (mOnRequestSoundCloudListener != null) {
if (s != null) {
mOnRequestSoundCloudListener.onRequestSoundClientSuccessful(s, mRequestId);
} else {
mOnRequestSoundCloudListener.onRequestSoundClientFailed(mRequestId);
}
}
}
public interface OnRequestSoundCloudListener {
void onRequestSoundClientSuccessful(String streamUrl, String request);
void onRequestSoundClientFailed(String request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment