Skip to content Skip to sidebar Skip to footer

How To Play Audio File From Url In Android

I need to play audio file from remote server in my app. I could play when I tested with localhost server (using WAMP). When the same file supplied from the server it is not working

Solution 1:

publicvoidonRadioClick(View v) {

    if (!isPLAYING) {
        isPLAYING = true;
        MediaPlayer mp = new MediaPlayer();
        try {
            mp.setDataSource(getString(R.string.audio_stream));
            mp.prepare();
            mp.start();
        } catch (IOException e) {
            Log.e(LOG_TAG, "prepare() failed");
        }
    } else {
        isPLAYING = false;
        stopPlaying();
    }
}

privatevoidstopPlaying() {
    mp.release();
    mp = null;
}

Solution 2:

The answer provided above provides synchronous fetching and playing, meaning currently executing thread will be blocked until prepare() is completed.

prepareAsync() can be used instead to "prepare" the stream asynchronously. You also will need to handle onPrepared() event to start playing.

mediaPlayer.setDataSource(URL here);
mediaPlayer.prepareAsync();

Add OnPrepared event handler:

mPlayer.setOnPreparedListener(newOnPreparedListener() {
    @OverridepublicvoidonPrepared(MediaPlayer mp) {
        mPlayer.start();
    }
});

Still, apparently there is no way to configure streaming buffer size. Frustrating...

Solution 3:

> import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.SeekBar;

import com.google.ads.Ad;
import com.google.ads.AdListener;
import com.google.ads.AdRequest;
import com.google.ads.AdRequest.ErrorCode;
import com.google.ads.InterstitialAd;

/**
 * @author Rashid Ali
 * @Date Sep 18, 2014
 * @Email <rashid.android.developer@gmail.com>
 * 
 */publicclassAudioPlayerActivityextendsActivityimplementsOnClickListener,
        OnTouchListener, OnCompletionListener, OnBufferingUpdateListener,
        AdListener {

    privateProgressDialog progressBar;

    privatestatic final StringAD_UNIT_ID_GOES_HERE = "ca-app-pub-5453344383403527/5064575693";
    privateInterstitialAd interstitialAd;

    privateImageButton buttonPlayPause;
    privateSeekBar seekBarProgress;

    privateMediaPlayer mediaPlayer;
    private int mediaFileLengthInMilliseconds; // this value contains the song// duration in milliseconds.// Look at getDuration() method// in MediaPlayer classprivate final Handler handler = newHandler();

    String audioName;

    @OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stubsuper.onCreate(savedInstanceState);
        setContentView(R.layout.activity_audio_player);

        interstitialAd = newInterstitialAd(this, AD_UNIT_ID_GOES_HERE);
        interstitialAd.setAdListener(this);
        AdRequest adRequest = newAdRequest();
        adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
        interstitialAd.loadAd(adRequest);

        initilizeUI();

        Intent intent = getIntent();
        audioName = intent.getStringExtra("audioName");

    }

    /** This method is used to Initialize UI Components. */privatevoidinitilizeUI() {
        buttonPlayPause = (ImageButton) findViewById(R.id.ButtonTestPlayPause);
        buttonPlayPause.setOnClickListener(this);
        seekBarProgress = (SeekBar) findViewById(R.id.SeekBarTestPlay);
        seekBarProgress.setMax(99);
        seekBarProgress.setOnTouchListener(this);

        mediaPlayer = newMediaPlayer();
        mediaPlayer.setOnBufferingUpdateListener(this);
        mediaPlayer.setOnCompletionListener(this);
    }

    /**
     * Method which updates the SeekBar primary progress by current song playing
     * position
     */privatevoidprimarySeekBarProgressUpdater() {
        seekBarProgress.setProgress((int) (((float) mediaPlayer
                .getCurrentPosition() / mediaFileLengthInMilliseconds) * 100)); // This// math// construction// give// a// percentage// of// "was playing"/"song length"if (mediaPlayer.isPlaying()) {
            Runnable notification = newRunnable() {
                publicvoidrun() {
                    primarySeekBarProgressUpdater();
                }
            };
            handler.postDelayed(notification, 1000);
        }
    }

    @OverridepublicvoidonBufferingUpdate(MediaPlayer mp, int percent) {
        /**
         * Method which updates the SeekBar secondary progress by current song
         * loading from URL position
         */
        seekBarProgress.setSecondaryProgress(percent);
    }

    @OverridepublicvoidonCompletion(MediaPlayer mp) {
        /**
         * MediaPlayer onCompletion event handler. Method which calls then song
         * playing is complete
         */// buttonPlayPause.setImageResource(R.drawable.button_play);
    }

    @OverridepublicbooleanonTouch(View v, MotionEvent event) {
        if (v.getId() == R.id.SeekBarTestPlay) {
            /**
             * Seekbar onTouch event handler. Method which seeks MediaPlayer to
             * seekBar primary progress position
             */if (mediaPlayer.isPlaying()) {
                SeekBar sb = (SeekBar) v;
                int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100)
                        * sb.getProgress();
                mediaPlayer.seekTo(playPositionInMillisecconds);
            }
        }
        returnfalse;
    }

    @OverridepublicvoidonClick(View v) {
        if (v.getId() == R.id.ButtonTestPlayPause) {
            /**
             * ImageButton onClick event handler. Method which start/pause
             * mediaplayer playing
             */try {
                mediaPlayer.setDataSource(audioName); // setup// song// from// http://www.hrupin.com/wp-content/uploads/mp3/testsong_20_sec.mp3// URL// to// mediaplayer// data// source
                mediaPlayer.prepare(); // you must call this method after setup// the datasource in setDataSource// method. After calling prepare() the// instance of MediaPlayer starts load// data from URL to internal buffer.
            } catch (Exception e) {
                e.printStackTrace();
            }

            mediaFileLengthInMilliseconds = mediaPlayer.getDuration(); // gets// the// song// length// in// milliseconds// from// URLif (!mediaPlayer.isPlaying()) {
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.pause_button);

            } else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.play_button);
            }
            primarySeekBarProgressUpdater();
        }
    }

    @OverridepublicvoidonBackPressed() {
        // TODO Auto-generated method stubsuper.onBackPressed();
        mediaPlayer.stop();
        this.finish();
    }

    @OverridepublicvoidonDismissScreen(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonFailedToReceiveAd(Ad arg0, ErrorCode arg1) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonLeaveApplication(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonPresentScreen(Ad arg0) {
        // TODO Auto-generated method stub

    }

    @OverridepublicvoidonReceiveAd(Ad ad) {
        // TODO Auto-generated method stubif (ad == interstitialAd) {
            interstitialAd.show();
        }
    }

}

<RelativeLayoutandroid:id="@+id/layout_header"android:layout_width="match_parent"android:layout_height="50dp"android:background="@drawable/header" ></RelativeLayout><RelativeLayoutandroid:id="@+id/ad_layout"android:layout_width="match_parent"android:layout_height="50dp"android:layout_below="@+id/layout_header" ><com.google.ads.AdViewandroid:id="@+id/googleads"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"ads:adSize="BANNER"ads:adUnitId="ca-app-pub-5453344383403527/9634376094"ads:loadAdOnCreate="true" ></com.google.ads.AdView></RelativeLayout><RelativeLayoutandroid:id="@+id/ad_layout"android:layout_width="match_parent"android:layout_height="50dp"android:layout_alignParentBottom="true" ><com.google.ads.AdViewandroid:id="@+id/googleads"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_centerHorizontal="true"ads:adSize="BANNER"ads:adUnitId="ca-app-pub-5453344383403527/2111109291"ads:loadAdOnCreate="true" ></com.google.ads.AdView></RelativeLayout><RelativeLayoutandroid:id="@+id/functional_layout"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_centerVertical="true" ><ImageButtonandroid:id="@+id/ButtonTestPlayPause"android:layout_width="50dp"android:layout_height="50dp"android:layout_marginLeft="10dp"android:src="@drawable/play_button" /><SeekBarandroid:id="@+id/SeekBarTestPlay"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentRight="true"android:layout_centerVertical="true"android:layout_marginLeft="10dp"android:layout_marginRight="10dp"android:layout_toRightOf="@+id/ButtonTestPlayPause" /></RelativeLayout>

Solution 4:

If you are writing Java programs to play media files, then the first port of call is the MediaPlayer class. Typical code to play a file using the streaming mechanism of MediaPlayer is

publicvoidonCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    try {
        Uriuri= Uri.parse("http://192.168.1.9/music/test.ogg");
        MediaPlayerplayer=newMediaPlayer();
        player.setAudioStreamType(AudioManager.STREAM_MUSIC);
        player.setDataSource(this, uri);
        player.prepare();
        player.start();
    } catch(Exception e) {
        System.out.println(e.toString());
    }
}

Wake Lock Permission - If your player application needs to keep the screen from dimming or the processor from sleeping, or uses the MediaPlayer.setScreenOnWhilePlaying() or MediaPlayer.setWakeMode() methods, you must request this permission.

<uses-permissionandroid:name="android.permission.WAKE_LOCK" />

Solution 5:

I used the following Kotlin extension for url streaming by using MediaPlayer

fun ImageButton.playFromUrl(
    url: String,
    onStart: MediaPlayer.() -> Unit
) {
    val audioAttributes = AudioAttributes.Builder()
        .setUsage(AudioAttributes.USAGE_MEDIA)
        .setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
        .build()

    MediaPlayer().apply {
        setAudioAttributes(audioAttributes)
        setDataSource(url)

        setOnPreparedListener {
            isEnabled = false
            start()
            setImageDrawable(context.getDrawableResource(R.drawable.ic_baseline_stop_24))
        }

        setOnCompletionListener {
            setImageDrawable(context.getDrawableResource(R.drawable.ic_baseline_volume_up_24))
            release()
            isEnabled = true
        }
    }.onStart()
}

the usage of above function like below

btnVoice.setOnSingleClickListener {
    if(it.isInternetAvailable()){
        (it as ImageButton).playFromUrl(phonetic.audio){
            prepareAsync()
        }
    }
}

Post a Comment for "How To Play Audio File From Url In Android"