使用MediaPlayer播放音乐文件的简单例子

来源:互联网 发布:mysql存储过程语法 编辑:程序博客网 时间:2024/06/08 11:22

之前温习android的知识,就想复习一下mediaplayer的知识点,Demo很简单,代码如下:

mediaplayer
先来布局文件:

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:id="@+id/activity_main"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context="com.example.myapplication.MainActivity">    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="horizontal">        <Button            android:id="@+id/btnPickAudio"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="onPick"            android:text="选取音乐" />        <Button            android:id="@+id/btnPickVideo"            android:layout_width="0dp"            android:layout_height="wrap_content"            android:layout_weight="1"            android:onClick="onPick"            android:text="选取视频" />    </LinearLayout>    <TextView        android:id="@+id/txvName"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:text="文件名" />    <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:orientation="vertical">        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:orientation="horizontal">            <Button                android:id="@+id/btnPlay"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:onClick="onMpPlay"                android:text="播放"                />            <Button                android:id="@+id/btnStop"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:onClick="onMpStop"                android:text="停止" />            <CheckBox                android:id="@+id/ckbLoop"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:checked="false"                android:onClick="onMpLoop"                android:text="重复播放" />        </LinearLayout>        <LinearLayout            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:gravity="right"            android:orientation="horizontal">            <Button                android:id="@+id/lgbBackForward"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:onClick="onMpBackWard"                android:text="后退" />            <Button                android:id="@+id/lgbForward"                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:onClick="onMpForward"                android:text="前进" />        </LinearLayout>    </LinearLayout>    <TextView        android:id="@+id/txvUri"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="20dp"        android:text="路径" /></LinearLayout>

Main文件代码:

public class MainActivity extends AppCompatActivity implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener {    Uri uri;    TextView txvName, txvUri;    boolean isVideo = false;    Button btnPlay, btnStop;    CheckBox ckbLoop;    MediaPlayer mper;    Toast tos;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        txvName = (TextView) findViewById(R.id.txvName);        txvUri = (TextView) findViewById(R.id.txvUri);        btnPlay = (Button) findViewById(R.id.btnPlay);        btnStop = (Button) findViewById(R.id.btnStop);        ckbLoop = (CheckBox) findViewById(R.id.ckbLoop);        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);//屏幕不随手机旋转        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);//屏幕竖屏        getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);//保持屏幕不休眠        uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.diantaiqingge);        txvName.setText("电台情歌");        txvUri.setText("程序内曲目:" + uri.toString());        mper = new MediaPlayer();        mper.setOnPreparedListener(this);        mper.setOnErrorListener(this);        mper.setOnCompletionListener(this);        tos = Toast.makeText(this, "", Toast.LENGTH_SHORT);        prepareMusic();    }    private void prepareMusic() {        btnPlay.setText("播放");        btnPlay.setEnabled(false);        btnStop.setEnabled(false);        try {            mper.reset();            mper.setDataSource(this, uri);            mper.setLooping(ckbLoop.isChecked());            mper.prepareAsync();        } catch (IOException e) {            tos.setText("指定音乐文件错误!" + e.toString());            tos.show();        }    }    public void onPick(View view) {        Intent it = new Intent(Intent.ACTION_GET_CONTENT);        if (view.getId() == R.id.btnPickAudio) {            it.setType("audio/*");            startActivityForResult(it, 100);        } else {            it.setType("video/*");            startActivityForResult(it, 101);        }    }    @Override    protected void onActivityResult(int requestCode, int resultCode, Intent data) {        super.onActivityResult(requestCode, resultCode, data);        if (resultCode == Activity.RESULT_OK) {            if (requestCode == 100) {                isVideo = false;                uri = convertUri(data.getData());                txvName.setText(isVideo ? "视频" : "音频" + uri.getLastPathSegment());                txvUri.setText("文件位置:" + uri.getPath());                if (!isVideo) {                    prepareMusic();                }            } else {                isVideo = true;            }        }    }    Uri convertUri(Uri uri) {        if (uri.toString().substring(0, 7).equals("content")) {//以content开头的图像文件需要转换成file开头的文件路径            String[] colName = {MediaStore.MediaColumns.DATA};//声明要查询的字段            Cursor cursor = getContentResolver().query(uri, colName, null, null, null);            cursor.moveToFirst();//移到查询结果的第一个记录            uri = Uri.parse("file://" + cursor.getString(0));//将路径转化为uri            cursor.close();        }        return uri;    }    @Override    public void onPrepared(MediaPlayer mediaPlayer) {        //当准备好时,让播放按钮起作用        btnPlay.setEnabled(true);    }    @Override    public void onCompletion(MediaPlayer mediaPlayer) {//当播放完毕时        mper.seekTo(0);//播放位置归0        btnPlay.setText("播放");        btnStop.setEnabled(false);    }    @Override    public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {        tos.setText("发生错误,停止播放");        tos.show();        return true;    }    public void onMpPlay(View v) {        //音乐播放        if (mper.isPlaying()) {//正在播放就暂停            mper.pause();            btnPlay.setText("继续");        } else {            mper.start();            btnPlay.setText("暂停");            btnStop.setEnabled(true);        }    }    public void onMpStop(View v) {        //音乐停止        mper.pause();        mper.seekTo(0);        btnPlay.setText("播放");        btnStop.setEnabled(false);    }    public void onMpLoop(View v) {        //是否循环        if (ckbLoop.isChecked()) {            mper.setLooping(true);        } else {            mper.setLooping(false);        }    }    public void onMpBackWard(View v) {        //前进        if (!btnPlay.isEnabled()) {            return;        }        int len = mper.getDuration();        int pos = mper.getCurrentPosition();        pos -= 10000;        if (pos < 0) {            pos = 0;        }        mper.seekTo(pos);        tos.setText("倒退10秒:" + pos / 1000 + "/" + len / 1000);        tos.show();    }    public void onMpForward(View v) {        //后退        if (!btnPlay.isEnabled()) {            return;        }        int len = mper.getDuration();        int pos = mper.getCurrentPosition();        pos += 10000;        if (pos > len) {//不可大于音频长度            pos = len;        }        mper.seekTo(pos);        tos.setText("前进10秒:" + pos / 1000 + "/" + len / 1000);        tos.show();    }    @Override    protected void onPause() {        super.onPause();        if (mper.isPlaying()) {            btnPlay.setText("继续");            mper.pause();        }    }    @Override    protected void onDestroy() {        super.onDestroy();        mper.release();    }}

需要注意的是:音频文件放在res的raw文件夹下,最好用英文
再用华为手机测试的时候,文件路径总是报null,360手机就没问题,同样的6.0。不管写什么,总觉得华为手机上出现的问题总是一大堆。。。将gradle的 targetSdkVersion 设为22以下就可以了,原因是Android6.0以上的系统权限需要手动申请,有点小麻烦。

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

知识点来源于网络,难免有重复,谅解。转载注明出处。

0 0
原创粉丝点击