developerXXX
developerXXX

Reputation: 689

play or pause multiple audio files in android

I have a question about playing/pausing multiple audio files in android. Our application loads audio files from the server using restful api. In the api there will have link to access the audio files (like http://www.common.com/folder/folder1/file1.mp4). Our application will list the name of the audio files in the list view in an android activity. Once a user taps on file1 then the file1 start play. And when user taps on another file, the file1 pause the playing and start playing for the tapped file. This should happen for all file.

Our doubt is, Do we need to use multiple instance of the media player for playing the different audio files. Like new MediaPlayer() object for each file? Can we handle this situation with a single instance of MediaPlayer? Does SoundPool helps in this situation?

Upvotes: 1

Views: 1870

Answers (1)

Mikaël Mayer
Mikaël Mayer

Reputation: 10681

Yes, Soundpool might help if you want to have this process of play/pause.

First you create a sound manager that is retained accross activity instances, and a map to link the audio file to the ID.

// Replace 10 with the maximum of sounds that you would like play at the same time.
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 100); 
HashMap<String, Integer> stringToSoundID = new HashMap<String, Integer>();
HashMap<Integer, Integer> soundIdToStreamID = new HashMap<Integer, Integer>();
Integer streamIDbeingPlayed= -1;

Then load all the sounds into the soundPool, keeping a link between the file and the sound ID.

for(String filePath: Files) {
  int soundID = soundPool.load(filePath, 1);
  stringToSoundID.put(filePath, soundID );
}

You can then have your function to play/pause a file like this:

void playFile(String filePath) {
  if(streamIDbeingPlayed!= -1) {
    soundPool.pause(streamIDbeingPlayed);
  }
  Integer soundID = stringToSoundID.get(filePath);
  Integer streamID = soundIdToStreamID.get(soundID);
  if(streamID == null) {
    streamIDbeingPlayed = soundPool.play (soundID, 1, 1, 1, -1, 1);
    soundIdToStreamID.put(soundID, streamIDbeingPlayed);
  } else {
    soundPool.resume(streamID);
    streamIDbeingPlayed = streamID;
  }
}

Upvotes: 1

Related Questions