TQC-303 mMediaPlayer
這是TQC的303題,
程式碼為自行撰寫,
僅供參考。
練習用mMediaPlayer,並處理相關事件
MediaPlayer.OnCompletionListener()
MediaPlayer.OnErrorListener()
package COM.TQC.GDD03;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
public class GDD03 extends Activity {
private ImageButton mButtonPlay, mButtonPause, mButtonStop;
private TextView mTextView;
private MediaPlayer mMediaPlayer;
private boolean bIsPaused = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/*透過findViewById建構子建立TextView與ImageView物件*/
mMediaPlayer = new MediaPlayer();
/* 將音樂以Import的方式儲存在res/raw/always.mp3 */
mMediaPlayer.create(this, R.raw.always);
findview();
setlistener();
}
@Override
/*覆寫主程式暫停狀態事件*/
protected void onPause()
{
// TODO Auto-generated method stub
try
{
}
catch (Exception e)
{
mTextView.setText(e.toString());
e.printStackTrace();
}
super.onPause();
}
public void findview()
{
mButtonPlay=(ImageButton)findViewById(R.id.imageButton1);
mButtonPause=(ImageButton)findViewById(R.id.imageButton2);
mButtonStop=(ImageButton)findViewById(R.id.imageButton3);
mTextView=(TextView)findViewById(R.id.textView1);
}
public void setlistener()
{
/* 執行播放音樂的按鈕 */
mButtonPlay.setOnClickListener(new ImageButton.OnClickListener()
{
/*覆寫OnClick事件*/
public void onClick(View v)
{
// TODO Auto-generated method stub
try
{
mMediaPlayer.start();
mTextView.setText(R.string.str_start);
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView.setText(e.toString());
e.printStackTrace();
}
}
});
/* 停止播放 */
mButtonStop.setOnClickListener(new ImageButton.OnClickListener()
{
// @Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
try
{
if (mMediaPlayer != null)
{
mMediaPlayer.stop();
mTextView.setText(R.string.str_close);
}
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView.setText(e.toString());
e.printStackTrace();
}
}
});
/* 暫停播放 */
mButtonPause.setOnClickListener(new ImageButton.OnClickListener()
{
//@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
try
{
mMediaPlayer.pause();
mTextView.setText(R.string.str_pause);
}
catch (Exception e)
{
// TODO Auto-generated catch block
mTextView.setText(e.toString());
e.printStackTrace();
}
}
});
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
public void onCompletion(MediaPlayer arg0)
{
try
{
mMediaPlayer.release();
mTextView.setText("release");
}
catch (Exception e)
{
mTextView.setText(e.toString());
e.printStackTrace();
}
}
});
mMediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener()
{
public boolean onError(MediaPlayer arg0, int arg1, int arg2)
{
// TODO Auto-generated method stub
try
{
}
catch (Exception e)
{
mTextView.setText(e.toString());
e.printStackTrace();
}
return false;
}
});
}
}
自我LV~