Sunday, July 21, 2013

Android: music play back

Summary:
  1. Copy the music file, eg: MP3, into the res\raw folder. if raw folder does not exist, create it. 
  2. Check R.*.java. a new id should be created. eg.: R.raw.music.
  3. import android.media.MediaPlayer;
  4. MediaPlayer player
  5. player = MediaPlayer.create(this.getApplicationContext(), R.raw.music);
  6. player.start();
  7. player.pause(); 
  8. player.seekTo(0); // seek to 0 millisec 
Alternatively, use SoundPool to manage a list of sound (eg.: sound effects for a game level): http://developer.android.com/reference/android/media/SoundPool.html
  1. import android.media.*
  2. SoundPool sndPool;
  3. sndPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); // max streams: 10; sample-rate converter quality. Currently has no effect. Use 0 for the default.
  4. int button01 = sndPool.load(this.getApplicationContext(), R.raw.button01, 1); // etc. can load more; priority of the sound. Currently has no effect. Use a value of 1 for future compatibility.
  5. (Activity) : this.setVolumeControlStream(AudioManager.STREAM_MUSIC); // to set Activity sound be controlled by hardware volume keys
  6. when it's time to play, sndPool.play(button01, 1, 1, 0, 0, 1);
    • left & right volume: 0 to 1.0
    • priority: 0 lowest
    • no loop: 0; -1 loop forever
    • play rate: 1.0

No comments: