Search code examples
androidandroid-mediaplayeraudio-streaming

Android Audio Streaming Service: MediaPlayer error -1004


I'm stuck on this problem:

I'm quite new to Android and I'm currently trying to develop a simple Service to stream audio from an URL data source, a Web Radio.
This Service has one of the simplest implementation of a MediaPlayer that I've ever found, something like:

MediaPlayer mediaPlayer = new MediaPlayer();
try {
    mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mediaPlayer.setDataSource(url);
    mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.start();
        }
    });
    mediaPlayer.prepareAsync();
}
catch (Exception ex) {
    ex.printStackTrace();
}

At the beginning I used a test URL, more specifically http://icecast.omroep.nl/radio1-bb-mp3, and everything worked fine.
Today I've been given the definitive URL: http://eu3.radioboss.fm:8037/live and MediaPlayer started giving me MEDIA_ERROR_IO (-1004).

I've read that this can be caused by an unsupported Media Format, but I don't know how I can get the encoding of the stream.
And the real problem is that I've absolutely NO control over the definitive URL.

Can someone suggest me how can I make the definitive audio source work?


Solution

  • At the end, it turned out that the simplest solution was to use ExoPlayer.

    As the Developer Guide says, MediaCodecVideoTrackRenderer and MediaCodecAudioTrackRenderer "can handle all audio and video formats supported by a given Android device".

    That's how I've initialized my Internet Radio using ExoPlayer:

    private static final int BUFFER_SEGMENT_SIZE = 64 * 1024;
    private static final int BUFFER_SEGMENT_COUNT = 256;
    
    private void initMediaPlayer() {
        // We create an ExoPlayer with argument 1 because
        // we are going to use exclusively an audio renderer
        ExoPlayer player = ExoPlayer.Factory.newInstance(1);
        // String with the url of the radio we want to play
        String url = "http://eu3.radioboss.fm:8037/live";
        Uri radioUri = Uri.parse(url);
        // Settings for our ExoPlayer
        Allocator allocator = new DefaultAllocator(BUFFER_SEGMENT_SIZE);
        String userAgent = Util.getUserAgent(this, "AudioStreamService");
        DataSource dataSource = new DefaultUriDataSource(this, null, userAgent);
        ExtractorSampleSource sampleSource = new ExtractorSampleSource(
            radioUri,
            dataSource,
            allocator,
            BUFFER_SEGMENT_SIZE * BUFFER_SEGMENT_COUNT
        );
        this.audioRenderer = new MediaCodecAudioTrackRenderer(sampleSource, MediaCodecSelector.DEFAULT);
        // Prepare ExoPlayer
        player.prepare(this.audioRenderer);
    }
    

    Hope this will help someone.