SoFunction
Updated on 2025-03-11

Android music player production Click song to play (II)

Last time we implemented the audio from our phone, and then put it in the list collection, and display it on the mobile phone interface with ListView. If you have not seen it, you can check out your blog:Android Music Player Production (I) Scan local music to display on your phone

This time, I continued to write the code directly based on the last time. A few lines of code can be clicked on the song and then the song will be played. The system has provided the object to play the audio, just use it directly. The details are as follows:

1. Declare a MediaPlayer

private MediaPlayer mediaPlayer;//Play audio

2. Instantiation

//initializationmediaPlayer = new MediaPlayer(); 

Then we have a MediaPlayer object to use

3. Set a click monitoring event for ListView in the initView method. If you click on the item, we can get the song address of this item, and then enter the method we created to play the audio:

(new () { 
      @Override 
      public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) { 
        //Create a method to play audio and pass the clicked address over        //(i).path is the address of the song        play((i).path); 
      } 
    }); 

Then the code of the play method:

/**
   * How to play audio
   */ 
  private void play(String path) { 
    //Reset the audio file before playing    try { 
      (); 
      //The audio path to be played by calling the method      (path); 
      //Asynchronous preparation of audio resources      (); 
      //Call the mediaPlayer's monitoring method, and the audio will respond to this method after the audio is ready.      (new () { 
        @Override 
        public void onPrepared(MediaPlayer mediaPlayer) { 
          ();//Start audio        } 
      }); 
 
    } catch (IOException e) { 
      (); 
    } 
  } 

In the play method, we call the mediaPlayer's asynchronous preparation method, because when the song is very large, if you do not use asynchronous preparation but directly prepare to play, it will cause playback stuttering; then call start() in the mediaPlayer's prepared listening method to start.

Continuous update

demo download address:Music player

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.