Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Play a sound file from internet when a button is clicked [duplicate]

I'm trying to play a sound file on button click but my sound URL comes form internet e.g http://www.example.com/sound.mp3. How can I play when button is clicked, using a Media Player.

Example: This is the way to Play Local file

      b.setOnClickListener(new View.OnClickListener() { 
        @Override public void onClick(View v) { 
        MediaPlayer mp = MediaPlayer.create(this, R.raw.mmmm); 
         mp.start();
         }
         });

I want play this sound http://www.example.com/sound.mp3 represent R.raw.mmmm , without downloading this sound.

like image 409
boyyes90 Avatar asked Aug 29 '11 09:08

boyyes90


1 Answers

Media Player has greate feature in android.You can handle all event that occurred.So this is the code to play a file(Either Local or Online Url)

String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepareAsync();
//You can show progress dialog here untill it prepared to play
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            //Now dismis progress dialog, Media palyer will start playing
            mp.start();
        }
    });
    mediaPlayer.setOnErrorListener(new OnErrorListener() {
        @Override
        public boolean onError(MediaPlayer mp, int what, int extra) {
            // dissmiss progress bar here. It will come here when MediaPlayer
            //  is not able to play file. You can show error message to user
            return false;
        }
    });
like image 123
Tofeeq Ahmad Avatar answered Sep 19 '22 14:09

Tofeeq Ahmad