2013-09-11 3 views
0

эй, я работаю над простым аудио-плеером. Приложение в Android. в этом приложении, я просто хочу играть звуковой файл из Интернета мой код выглядит следующим образом:Начало с Android-плеером Android

static MediaPlayer mPlayer; 
Button buttonPlay; 
Button buttonStop; 
String url = "http://android.programmerguru.com/wp-content/uploads/2013/04/hosannatelugu.mp3"; 
@Override 
public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.main); 

    buttonPlay = (Button) findViewById(R.id.play); 
    buttonPlay.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      mPlayer = new MediaPlayer(); 
      mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC); 
      try { 
       mPlayer.setDataSource(url); 
      } catch (IllegalArgumentException e) { 
       Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
      } catch (SecurityException e) { 
       Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
      } catch (IllegalStateException e) { 
       Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
      } catch (IOException e) { 
       e.printStackTrace(); 
      } 
      try { 
       mPlayer.prepare(); 
       Toast.makeText(getApplicationContext(), "Preparing!", Toast.LENGTH_LONG).show(); 
       Log.i("info","Preparing!"); 
      } catch (IllegalStateException e) { 
       Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
      } catch (IOException e) { 
       Toast.makeText(getApplicationContext(), "You might not set the URI correctly!", Toast.LENGTH_LONG).show(); 
      } 
      Toast.makeText(getApplicationContext(), "Prepared!", Toast.LENGTH_LONG).show(); 
      Toast.makeText(getApplicationContext(), "Size="+(mPlayer.getDuration()/100)+"  isPlaying="+mPlayer.isPlaying()+"  isLooping="+mPlayer.isLooping(), Toast.LENGTH_LONG).show(); 
      Log.i("info","Prepared!"); 
      mPlayer.start(); 
      Toast.makeText(getApplicationContext(), "Size="+(mPlayer.getDuration()/100)+"  isPlaying="+mPlayer.isPlaying()+"  isLooping="+mPlayer.isLooping(), Toast.LENGTH_LONG).show(); 

     } 
    }); 

    buttonStop = (Button) findViewById(R.id.stop); 
    buttonStop.setOnClickListener(new OnClickListener() { 

     public void onClick(View v) { 
      // TODO Auto-generated method stub 
      if(mPlayer!=null && mPlayer.isPlaying()){ 
       mPlayer.stop(); 
      } 
     } 
    }); 
} 

protected void onDestroy() { 
    super.onDestroy(); 
    // TODO Auto-generated method stub 
    if (mPlayer != null) { 
     mPlayer.release(); 
     mPlayer = null; 
    } 
} 

public void onCompletion(MediaPlayer mp) { 
    Toast.makeText(getApplicationContext(), "Completed", Toast.LENGTH_LONG).show(); 

} 

все работает плавно, но музыка не начинает

+0

Добавить

+0

Я получаю тост, который говорит, что музыка не играет –

+0

@ Дайте! я уже указал –

ответ

0

Тогда попробуйте это ,,,

import android.media.MediaPlayer; 
import android.media.MediaPlayer.OnBufferingUpdateListener; 
import android.media.MediaPlayer.OnCompletionListener; 
import android.net.Uri; 
import android.os.Build; 
import android.os.Bundle; 
import android.os.Environment; 
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.Button; 
import android.widget.ImageButton; 
import android.widget.ImageView; 
import android.widget.SeekBar; 
import android.widget.TextView; 
import android.widget.Toast; 
import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.DownloadManager; 
import android.content.Context; 


@SuppressLint({ "NewApi", "DefaultLocale" }) 
public class Detail extends Activity implements OnClickListener, OnTouchListener, 
           OnCompletionListener, OnBufferingUpdateListener{ 
    String url; 
    String nameFile; 
    String name; 
    boolean isBack = false; 
    private ImageButton buttonPlayPause; 
    private SeekBar seekBarProgress; 

    private MediaPlayer mediaPlayer; 
    private int mediaFileLengthInMilliseconds; // this value contains the song duration in milliseconds. Look at getDuration() method in MediaPlayer class 

    private final Handler handler = new Handler(); 
    private ltv.model.MSong mSong; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.detail);  

     // FOR PLAY MP3 FILE 
     url = "mp3 link"; 
     initView(); 
    } 

    /** This method initialise all the views in project*/ 
    private void initView() { 
     buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause); 
     buttonPlayPause.setOnClickListener(this); 

     seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay); 
     seekBarProgress.setMax(99); // It means 100% .0-99 
     seekBarProgress.setOnTouchListener(this); 

     mediaPlayer = new MediaPlayer(); 
     mediaPlayer.setOnBufferingUpdateListener(this); 
     mediaPlayer.setOnCompletionListener(this); 
    } 

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

    @Override 
    public void onClick(View v) { 
     if(v.getId() == R.id.ButtonTestPlayPause){ 
      /** ImageButton onClick event handler. Method which start/pause mediaplayer playing */ 
      try { 
       mediaPlayer.setDataSource(url); 
       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 URL 

      if(!mediaPlayer.isPlaying()){ 
       mediaPlayer.start(); 
       buttonPlayPause.setImageResource(R.drawable.button_pause); 
      }else { 
       mediaPlayer.pause(); 
       buttonPlayPause.setImageResource(R.drawable.button_play); 
      } 

      primarySeekBarProgressUpdater(); 
     } 
    } 

    @Override 
    public boolean onTouch(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); 
      } 
     } 
     return false; 
    } 

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

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

    @Override 
    public void onBackPressed() { 
     if (isBack) { 
      super.onBackPressed(); 
     } else { 
      if (mediaPlayer != null) { 
       if (mediaPlayer.isPlaying()) { 
        back(); 
       } else { 
        super.onBackPressed(); 
       } 
      } else { 
       super.onBackPressed(); 
      } 
     } 
    } 

} 
+0

, где я получил полный исходный код. –

+0

нормально, весь источник находится в http: //www.hrupin. com/2011/02/example-of-streaming-mp3-mediafile-with-android-mediaplayer-class, и есть еще один пример, попробуйте это тоже http://www.java2s.com/Code/Android/Media/PlayMp3filefromaUrl .htm –

Смежные вопросы