2017-07-21 27 views
0

我正在開發一個音頻播放器的應用程序。我想播放來自url的音頻,我正在做代碼,但它播放本地目錄的音頻,即原始文件夾。我想從播放列表中一次播放單個URL的歌曲,如何在doinbackground方法中實現代碼來播放單個文件。在下面的代碼中從url播放音頻需要做些什麼?建議我!如何從android中的URL播放音頻文件?

public class RelaxationLvAudioPlayerActivity1 extends Activity implements SeekBar.OnSeekBarChangeListener { 

    private ImageButton btnPlay; 
    private ImageButton btnForward; 
    private ImageButton btnBackward; 
    private ImageButton btnNext; 
    private ImageButton btnPrevious; 
    private ImageButton btnPlaylist; 
    private ImageButton btnRepeat; 
    private ImageButton btnShuffle; 
    private SeekBar songProgressBar; 
    private TextView songTitleLabel; 
    private TextView songCurrentDurationLabel; 
    private TextView songTotalDurationLabel; 
    // Media Player 
    private MediaPlayer mp; 
    // Handler to update UI timer, progress bar etc,. 
    private Handler mHandler = new Handler();; 
    private AudioPlayerManager songManager; 
    private Utilities utils; 
    private int seekForwardTime = 5000; // 5000 milliseconds 
    private int seekBackwardTime = 5000; // 5000 milliseconds 
    private int currentSongIndex = 0; 
    private boolean isShuffle = false; 
    private boolean isRepeat = false; 
    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_relaxationlv_audioplayer); 

     // All player buttons 
     btnPlay = (ImageButton) findViewById(R.id.btnPlay); 
     // btnForward = (ImageButton) findViewById(R.id.btnForward); 
     // btnBackward = (ImageButton) findViewById(R.id.btnBackward); 
     btnNext = (ImageButton) findViewById(R.id.btnNext); 
     btnPrevious = (ImageButton) findViewById(R.id.btnPrevious); 
     btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist); 
     // btnRepeat = (ImageButton) findViewById(R.id.btnRepeat); 
     //  btnShuffle = (ImageButton) findViewById(R.id.btnShuffle); 
     songProgressBar = (SeekBar) findViewById(R.id.songProgressBar); 
     songTitleLabel = (TextView) findViewById(R.id.songTitle); 
     songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel); 
     songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel); 

     // Mediaplayer 
     mp = new MediaPlayer(); 
     songManager = new AudioPlayerManager(); 
     utils = new Utilities(); 

     // Listeners 
     songProgressBar.setOnSeekBarChangeListener(this); // Important 

     // Getting all songs list 
     songsList = songManager.getPlayList(); 

     // By default play first song 
     playSong(0); 

     /** 
     * Play button click event 
     * plays a song and changes button to pause image 
     * pauses a song and changes button to play image 
     * */ 
     btnPlay.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // check for already playing 
       if(mp.isPlaying()){ 
        if(mp!=null){ 
         mp.pause(); 
         // Changing button image to play button 
         btnPlay.setImageResource(R.drawable.btn_play); 
        } 
       }else{ 
        // Resume song 
        if(mp!=null){ 
         mp.start(); 
         // Changing button image to pause button 
         btnPlay.setImageResource(R.drawable.btn_pause); 
        } 
       } 

      } 
     }); 

     btnNext.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       // check if next song is there or not 
       if(currentSongIndex < (songsList.size() - 1)){ 
        playSong(currentSongIndex + 1); 
        currentSongIndex = currentSongIndex + 1; 
       }else{ 
        // play first song 
        playSong(0); 
        currentSongIndex = 0; 
       } 

      } 
     }); 

     /** 
     * Back button click event 
     * Plays previous song by currentSongIndex - 1 
     * */ 
     btnPrevious.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       if(currentSongIndex > 0){ 
        playSong(currentSongIndex - 1); 
        currentSongIndex = currentSongIndex - 1; 
       }else{ 
        // play last song 
        playSong(songsList.size() - 1); 
        currentSongIndex = songsList.size() - 1; 
       } 

      } 
     }); 


     btnPlaylist.setOnClickListener(new View.OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 
       Intent i = new Intent(getApplicationContext(), AudioPlayerListActivity.class); 
       startActivityForResult(i, 100); 
      } 
     }); 

    } 

    /** 
    * Receiving song index from playlist view 
    * and play the song 
    * */ 
    @Override 
    protected void onActivityResult(int requestCode, 
            int resultCode, Intent data) { 
     super.onActivityResult(requestCode, resultCode, data); 
     if(resultCode == 100){ 
      currentSongIndex = data.getExtras().getInt("songIndex"); 
      // play selected song 
      playSong(currentSongIndex); 
     } 

    } 

    /** 
    * Function to play a song 
    * @param songIndex - index of song 
    * */ 
    public void playSong(int songIndex){ 
     // Play song 
     try { 
      mp.reset(); 
      mp.setDataSource(songsList.get(songIndex).get("songPath")); 
      mp.prepare(); 
      mp.start(); 
      // Displaying Song title 
      String songTitle = songsList.get(songIndex).get("songTitle"); 
      songTitleLabel.setText(songTitle); 

      // Changing Button Image to pause image 
      btnPlay.setImageResource(R.drawable.btn_pause); 

      // set Progress bar values 
      songProgressBar.setProgress(0); 
      songProgressBar.setMax(100); 

      // Updating progress bar 
      updateProgressBar(); 
     } catch (IllegalArgumentException e) { 
      e.printStackTrace(); 
     } catch (IllegalStateException e) { 
      e.printStackTrace(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
    } 

    /** 
    * Update timer on seekbar 
    * */ 
    public void updateProgressBar() { 
     mHandler.postDelayed(mUpdateTimeTask, 100); 
    } 

    /** 
    * Background Runnable thread 
    * */ 
    private Runnable mUpdateTimeTask = new Runnable() { 
     public void run() { 
      long totalDuration = mp.getDuration(); 
      long currentDuration = mp.getCurrentPosition(); 

      // Displaying Total Duration time 
      songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration)); 
      // Displaying time completed playing 
      songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration)); 

      // Updating progress bar 
      int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration)); 
      //Log.d("Progress", ""+progress); 
      songProgressBar.setProgress(progress); 

      // Running this thread after 100 milliseconds 
      mHandler.postDelayed(this, 100); 

      /// mHandler.removeCallbacks(mUpdateTimeTask); //add this line 
     } 
    }; 

    /** 
    * 
    * */ 
    @Override 
    public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) { 

    } 

    /** 
    * When user starts moving the progress handler 
    * */ 
    @Override 
    public void onStartTrackingTouch(SeekBar seekBar) { 
     // remove message Handler from updating progress bar 
     mHandler.removeCallbacks(mUpdateTimeTask); 
    } 

    /** 
    * When user stops moving the progress hanlder 
    * */ 
    @Override 
    public void onStopTrackingTouch(SeekBar seekBar) { 
     mHandler.removeCallbacks(mUpdateTimeTask); 
     int totalDuration = mp.getDuration(); 
     int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration); 

     // forward or backward to certain seconds 
     mp.seekTo(currentPosition); 

     // update timer progress again 
     updateProgressBar(); 
    } 
    @Override 
    protected void onDestroy() { 
     if (mUpdateTimeTask != null) 
      mHandler.removeCallbacks(mUpdateTimeTask); 
     super.onDestroy(); 
     mp.release(); 
    } 
} 



public class AudioPlayerManager{ 
    // SDCard Path 
    // final String MEDIA_PATH = new String(Environment.getExternalStorageDirectory().getPath()); 
      final String MEDIA_PATH = "/sdcard/songs/"; 
    //  private String MEDIA_PATH =Environment.getExternalStorageDirectory().getPath(); 

    private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>(); 

    // Constructor 
    public AudioPlayerManager(){ 

    } 

    /** 
    * Function to read all mp3 files from sdcard 
    * and store the details in ArrayList 
    * */ 
    public ArrayList<HashMap<String, String>> getPlayList(){ 
     // File home = new File(MEDIA_PATH); 
     File home = new File(MEDIA_PATH); 

     if (home.listFiles(new FileExtensionFilter()).length > 0) { 
      for (File file : home.listFiles(new FileExtensionFilter())) { 
       HashMap<String, String> song = new HashMap<String, String>(); 
       song.put("songTitle", file.getName().substring(0, (file.getName().length() - 4))); 
       song.put("songPath", file.getPath()); 

       // Adding each song to SongList 
       songsList.add(song); 
      } 
     } 
     // return songs list array 
     return songsList; 
    } 

    /** 
    * Class to filter files which are having .mp3 extension 
    * */ 
    class FileExtensionFilter implements FilenameFilter { 
     public boolean accept(File dir, String name) { 
      return (name.endsWith(".mp3") || name.endsWith(".MP3")); 
     } 
    } 
} 
+0

加入Android的媒體播放器標籤 –

+0

我如何做到這一點? – Rohu

回答

0

你可以試試這個

try { 

    mp.setAudioStreamType(AudioManager.STREAM_MUSIC); 
    mp.setDataSource("your url"); 
    mp.prepare(); 
    mp.start();  
} catch (Exception e) { 
    // handle exception 
} 
+0

我想用我的媒體播放器設計播放音頻 – Rohu

+0

我該怎麼做? – Rohu

+0

只需將此代碼添加到您想要播放視頻的自定義媒體播放器中即可 –