Android使用MediaPlayer播放mp3音乐示例



package com.mzwu.www;

import android.content.res.AssetFileDescriptor;
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.Toast;
import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    //播放器
    private MediaPlayer mp = new MediaPlayer();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        //开始播放
        Button btnPlay = (Button)findViewById(R.id.button);
        btnPlay.setOnClickListener(new OnClickListener(){
            public void onClick(View v) {
                String soundfile = ((EditText)findViewById(R.id.editText)).getText().toString();
                try {
                    mp.reset();
                    if(soundfile.startsWith("http:")){
                        mp.setDataSource(soundfile);
                    }else{
                        AssetFileDescriptor fileDescriptor = MainActivity.this.getAssets().openFd(soundfile);
                        mp.setDataSource(fileDescriptor.getFileDescriptor(),
                                fileDescriptor.getStartOffset(),
                                fileDescriptor.getLength());
                        fileDescriptor.close();
                    }
                    mp.prepare();
                    mp.start();
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalStateException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        //播放结束
        mp.setOnCompletionListener(new MediaPlayer.OnCompletionListener(){
            public void onCompletion(MediaPlayer mp) {
                Toast.makeText(MainActivity.this, "播放结束!", Toast.LENGTH_SHORT).show();
            }
        });
    }

    //释放播放器占用的资源
    @Override
    protected void onDestroy() {
        if(mp != null)
        {
            mp.release();
        }
        super.onDestroy();
    }
}


参考资料

[1].深入Android MediaPlayer的使用方法详解:http://www.jb51.net/article/38722.htm
[2].Android MediaPlayer基本使用方式:http://blog.csdn.net/ddna/article/details/5176233
[3].MediaPlayer实现列表选歌:http://www.cnblogs.com/snake-hand/archive/2013/02/22/2922923.html
[4].创建OnClickListener方法报错的解决办法:http://blog.csdn.net/wpyily/article/details/46503709

评论: 0 | 引用: 0 | 查看次数: 503
发表评论
登录后再发表评论!