Playing a music file while downloading it

983 views Asked by At

I'm developing a music download App that basically does webscraping across differents torrent platforms and get the torrents. I want to play some music torrent files while I'm downloading them. I have a Service that basically takes care of doing all this. I set a buffer that waits until the torrent file Its at least 25% downloaded, then I use the MediaPlayer class to start playing the file. The music starts playing OK, but It stops after a while, as if It couldn't play more than that 25%. I tried using both the Android's MediaPlayer class and the FFmpegMediaPlayer library. I tried using several configs:

MediaPlayer mediaPlayer = new MediaPlayer();
        FileInputStream fis = null;
        try {
            fis = new FileInputStream(mCurrentTrack);
            mediaPlayer.setDataSource(fis.getFD());
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mediaPlayer) {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.prepareAsync();
        } catch (Exception e) {
            Log.w(APP_TAG, String.format("Something went wrong while trying to play the torrent stream: " + e.toString()));
        }

mCurrentTrack is the path to the mp3 file that I downloaded into my Download folder in the external storage.

I tried using AudioManager.STREAM_MUSIC. I tried using the sync prepare() method and then calling the start() method. I triead opening the file with a new File(mCurrentTrack) before start playing It and setting It as readeable and writable. I tried many combinations, but always is the same, the music plays a few seconds and then stops. When I check the external storage, the file ends up being fully downloaded without trouble.

The library that I'm using to download the torrent files is this one TorrentStream-Android

Any tip or idea about how play this file while its being downloaded in the fly, would be appreciated.

1

There are 1 answers

0
4gus71n On

As someone pointed out here. Using the ExoMedia player library solved the issue. Here's the snippet that I used to get it working:

compile 'com.devbrackets.android:exomedia:3.1.0'

final EMAudioPlayer mediaPlayer = new EMAudioPlayer (getApplicationContext());
            mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
                @Override
                public void onPrepared() {
                    mediaPlayer.start();
                }
            });
            mediaPlayer.setDataSource(getApplicationContext(), Uri.parse(mCurrentTrack));
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.prepareAsync();