1

我可以在我的 Android 应用程序中播放 SoundCloud 中的曲目吗?我正在尝试这段代码,但它不起作用:

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) {

    }
4

2 回答 2

8

我在尝试从 Android 播放 Soundcloud 流时遇到了同样的问题。

为我解决的问题是将以下权限添加到我的 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" />

对我来说,这是一个面对面的时刻。这是我的媒体播放器实现。

对于我的媒体播放器,我有一个实现的类

MediaPlayer.OnPreparedListener

在该类中,我使用以下代码来设置 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();

在我的onPrepared回调中,我只是开始播放流。

@Override
public void onPrepared(MediaPlayer mediaPlayer) {
    mMediaPlayer.start();
}
于 2013-07-28T19:04:11.027 回答
0

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();
        //...
    }
}
于 2013-03-31T18:05:24.087 回答