Play SoundCloud Track

烈酒焚心 提交于 2019-12-18 13:48:20

问题


can i play a track from SoundCloud in my android app? I'm trying this code but it doesn't works:

String res = "https://api.soundcloud.com/tracks/84973999/stream?client_id=cd9d2e5604410d714e32642a4ec0eed4";

MediaPlayer mp = new MediaPlayer();
try {
        mp.setDataSource(res);
        mp.prepare();
        mp.start();
    } catch (IOException e) {

    }

回答1:


I was having the same problem trying to play a Soundcloud stream from Android.

What fixed it for me was adding the following permissions to my AndroidManifest.xml

<permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.INTERNET" />
<permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

For me it was a facepalm moment. Here is my mediaplayer implementation.

For my mediaplayer I have a class that implements

MediaPlayer.OnPreparedListener

And in that class I use the following code to setup the MediaPlayer.

 mMediaPlayer = new MediaPlayer();
 mMediaPlayer.setOnPreparedListener(this);
 mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    try{
        mMediaPlayer.setDataSource("http://api.soundcloud.com/tracks/7399237/stream?client_id=XXX");
    }catch (IllegalArgumentException e){
        e.printStackTrace();

    } catch (IOException e) {
        e.printStackTrace();

    }
    mMediaPlayer.prepareAsync();

And in my onPrepared callback I simply start playing the stream.

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    mMediaPlayer.start();
}



回答2:


trying adding this before you set data source

mp.setAudioStreamType(AudioManager.STREAM_MUSIC);

there have also been issues noted when using MediaPlayer with URL redirects. You may need to resolve the redirects first, then set your datasource accordingly

To get the redirected url you can do soemthing like this using the soundcloud java-api-wrapper

HttpResponse resp = wrapper.get(Request.to(res));
if (resp.getStatusLine().getStatusCode() == HttpStatus.SC_MOVED_TEMPORARILY) {
    final Header location = resp.getFirstHeader("Location");
    if (location != null && location.getValue() != null) {
        String redirectedStream = location.getValue();
        //...
    }
}


来源:https://stackoverflow.com/questions/15732553/play-soundcloud-track

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!