MediaPlayer App用法
public class MainActivity extends Activity implements OnClickListener { private static final String TAG = "CM-MainActivity"; private MediaPlayer mMediaPlayer = null; private Button mPlayBtn; private Button mStopBtn; boolean isPlaying = false; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()"); super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mPlayBtn = (Button) findViewById(R.id.play); mPlayBtn.setOnClickListener(this); mStopBtn = (Button) findViewById(R.id.stop); mStopBtn.setOnClickListener(this); } @Override protected void onDestroy() { if (isPlaying && mMediaPlayer != null) { Log.d(TAG, "stop()"); mMediaPlayer.stop(); mMediaPlayer.release(); isPlaying = false; } super.onDestroy(); } @Override public void onClick(View view) { switch (view.getId()) { case R.id.play: if (mMediaPlayer == null) { Log.d(TAG, "new MediaPlayer()"); mMediaPlayer = new MediaPlayer(); } else { Log.d(TAG, "reset()"); mMediaPlayer.reset(); } try { Log.d(TAG, "setDataSource()"); mMediaPlayer.setDataSource("/storage/sdcard0/cfy.mp3"); Log.d(TAG, "prepare()"); mMediaPlayer.prepare(); Log.d(TAG, "start()"); mMediaPlayer.start(); isPlaying = true; } catch (Exception e) { e.printStackTrace(); } break; case R.id.stop: if (mMediaPlayer != null) { Log.d(TAG, "stop()"); mMediaPlayer.stop();
//mMediaPlayer.release(); //release后就结束了 再使用这个mMediaPlayer就会抛出异常,所以这句不要 isPlaying = false; } break; } } }

release()后 mMediaPlayer != null mMediaPlayer不能再被使用 除非重新new MediaPlayer()
offload模式下 session是MediaPlayer的标记,如果不给MediaPlayer重新赋值,那么session不会改变,但是output会变化。
04-15 12:46:52.159 347 19023 V AudioPolicyManager: startOutput() output 169, stream 3, session 162, drmFlag 00000000
04-15 12:46:58.825 347 1040 V AudioPolicyManager: stopOutput() output 169, stream 3, session 162, playbackId 0
04-15 12:47:03.091 347 19053 V AudioPolicyManager: startOutput() output 171, stream 3, session 162, drmFlag 00000000
04-15 12:47:04.763 347 1040 V AudioPolicyManager: stopOutput() output 171, stream 3, session 162, playbackId 0
04-15 12:47:12.090 347 19089 V AudioPolicyManager: startOutput() output 173, stream 3, session 162, drmFlag 00000000
04-15 12:47:16.543 347 1040 V AudioPolicyManager: stopOutput() output 173, stream 3, session 162, playbackId 0

浙公网安备 33010602011771号