Android成長之路-音樂播放器的實現

來源:互聯網
上載者:User

strings.xml

<?xml version="1.0" encoding="utf-8"?><resources>    <string name="app_name">MusicPlayer</string>    <string name="music_name">曲目</string>    <string name="play_text">播放</string>    <string name="pause_text">暫停</string>    <string name="continue_text">繼續</string>    <string name="reset_text">重設</string>    <string name="stop_text">停止</string>    <string name="choose_text">選擇</string>    <string name="notfoundfile_text">媒體檔案不存在</string>    <string name="notfoundSdcard_text">SDcard不存在</string></resources>

 

 

 

main.xml

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="fill_parent"    android:orientation="vertical" >    <TextView        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:text="@string/music_name" />    <TableLayout         android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:stretchColumns="0" >        <TableRow >        <EditText            android:id="@+id/musicEt"            android:layout_width="fill_parent"            android:layout_height="wrap_content"            android:text="l.mp3" />        <Button            android:id="@+id/chooseBtn"            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:text="@string/choose_text" />                </TableRow>    </TableLayout>    <SeekBar        android:id="@+id/seekBar"        android:layout_width="fill_parent"        android:layout_height="wrap_content" />    <SeekBar        android:id="@+id/seekBarSound"       android:layout_width="fill_parent"        android:layout_height="wrap_content"              android:max="100"               android:progress="10"/>              />        <TextView        android:id="@+id/time"         android:layout_width="fill_parent"        android:layout_height="wrap_content"        />    <TableLayout        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:stretchColumns="*" >        <TableRow >            <Button                android:id="@+id/playBtn"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/play_text" />            <Button                android:id="@+id/pauseBtn"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/pause_text" />            <Button                android:id="@+id/stopBtn"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:text="@string/stop_text" />        </TableRow>    </TableLayout></LinearLayout>

 

MusicPlayerActivity.java

package cn.csdn.playle;import java.io.File;import java.io.IOException;import android.app.Activity;import android.content.Context;import android.content.Intent;import android.media.AudioManager;import android.media.MediaPlayer;import android.os.Bundle;import android.os.Environment;import android.os.Handler;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.EditText;import android.widget.SeekBar;import android.widget.SeekBar.OnSeekBarChangeListener;import android.widget.TextView;import android.widget.Toast;public class MusicPlayerActivity extends Activity implements OnClickListener,OnSeekBarChangeListener {EditText musicEt;Button playBtn, pauseBtn, stopBtn, chooseBtn;TextView time;AudioManager audiomanage;int maxVolume, currentVolume;SeekBar seekBar, seekBarSound;MediaPlayer player = null;File file = null;int position = 0;int i = 0;Handler handler = new Handler();public void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);player = new MediaPlayer();findViews();}private void findViews() {musicEt = (EditText) this.findViewById(R.id.musicEt);playBtn = (Button) this.findViewById(R.id.playBtn);pauseBtn = (Button) this.findViewById(R.id.pauseBtn);stopBtn = (Button) this.findViewById(R.id.stopBtn);chooseBtn = (Button) this.findViewById(R.id.chooseBtn);seekBar = (SeekBar) this.findViewById(R.id.seekBar);seekBarSound = (SeekBar) this.findViewById(R.id.seekBarSound);time = (TextView) this.findViewById(R.id.time);time.setOnClickListener(this);playBtn.setOnClickListener(this);pauseBtn.setOnClickListener(this);stopBtn.setOnClickListener(this);stopBtn.setEnabled(false);pauseBtn.setEnabled(false);seekBar.setOnSeekBarChangeListener(this);chooseBtn.setOnClickListener(new OnClickListener() {public void onClick(View v) {Intent intent = new Intent(MusicPlayerActivity.this,MusicListActivity.class);startActivity(intent);}});audiomanage = (AudioManager) getSystemService(Context.AUDIO_SERVICE);maxVolume = audiomanage.getStreamMaxVolume(AudioManager.STREAM_MUSIC); // 擷取系統最大音量seekBarSound.setMax(maxVolume); // 拖動條最高值與系統最大聲匹配currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC); // 擷取當前值seekBarSound.setProgress(currentVolume);seekBarSound.setOnSeekBarChangeListener(new OnSeekBarChangeListener() // 調音監聽器{public void onProgressChanged(SeekBar arg0, int progress,boolean fromUser) {audiomanage.setStreamVolume(AudioManager.STREAM_MUSIC,progress, 0);currentVolume = audiomanage.getStreamVolume(AudioManager.STREAM_MUSIC); // 擷取當前值seekBarSound.setProgress(currentVolume);}public void onStartTrackingTouch(SeekBar seekBar) {}public void onStopTrackingTouch(SeekBar seekBar) {}});Intent intent = this.getIntent();String name = intent.getStringExtra("name");musicEt.setText(name);}public void onClick(View v) {String fileName = musicEt.getText().toString().trim();// 擷取sdcard的狀態是否已載入 (MEDIA_MOUNTED 載入狀態)if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {file = new File(Environment.getExternalStorageDirectory(), fileName);// 判斷所播放的媒體檔案是否存在if (file.exists()) {try {switch (v.getId()) {// 返回一個int值case R.id.playBtn:playMusic(file);break;case R.id.pauseBtn:if (player.isPlaying()) {player.pause();pauseBtn.setText(R.string.continue_text);} else {player.start();pauseBtn.setText(R.string.pause_text);}break;case R.id.stopBtn:player.stop();stopBtn.setEnabled(false);seekBar.setProgress(0);if (playBtn.getText().toString().equals("重設")) {playBtn.setText(R.string.play_text);}if (pauseBtn.getText().toString().equals("繼續")) {pauseBtn.setText(R.string.pause_text);pauseBtn.setEnabled(false);} else {pauseBtn.setEnabled(false);}break;}} catch (IllegalArgumentException e) {Log.e("TAG", e.toString());} catch (IllegalStateException e) {Log.e("TAG", e.toString());} catch (IOException e) {Log.e("TAG", e.toString());}} else {Toast.makeText(this, R.string.notfoundfile_text,Toast.LENGTH_LONG).show();}}else {Toast.makeText(this, R.string.notfoundSdcard_text,Toast.LENGTH_LONG).show();}}protected void onDestroy() {if (player != null) {if (player.isPlaying()) {player.stop();}player.release();}super.onDestroy();}protected void onPause() {if (player != null) {if (player.isPlaying()) {player.pause();}}super.onPause();}private void playMusic(File file) throws IllegalStateException, IOException {if (musicEt.getText().toString() == null|| "".equals(musicEt.getText().toString())) {Toast.makeText(this, "沒有選中歌曲", Toast.LENGTH_LONG).show();} else {if (player != null) {pauseBtn.setEnabled(true);player.reset();player.setDataSource(file.getAbsolutePath());player.prepare();player.start();playBtn.setText(R.string.reset_text);run();}if (playBtn.getText().toString().equals("重設")) {pauseBtn.setEnabled(true);stopBtn.setEnabled(true);}if (pauseBtn.getText().toString().equals("繼續")) {pauseBtn.setText(R.string.pause_text);}}}private void run() {new Thread(new Runnable() {public void run() {while (player != null) {int TIME = player.getDuration();seekBar.setMax(TIME);// 擷取歌曲的最大值position = player.getCurrentPosition();// 返回當前播放進度值seekBar.setProgress(position);try {Thread.sleep(3000);} catch (InterruptedException e) {e.printStackTrace();}}}}).start();}public void onProgressChanged(SeekBar seekBar, int progress,boolean fromUser) {}public void onStartTrackingTouch(SeekBar seekBar) {player.seekTo(seekBar.getProgress());}public void onStopTrackingTouch(SeekBar seekBar) {player.seekTo(seekBar.getProgress());}}

 

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.