自制最简Android MusicPlayer

来源:互联网 发布:信号处理与数据分析 编辑:程序博客网 时间:2024/05/22 14:34

播放的文件放到assets文件夹中,文件名 1.mp3


MainActivity

package com.media.player;import java.io.IOException;import android.media.MediaPlayer;import android.os.Bundle;import android.app.Activity;import android.content.res.AssetFileDescriptor;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;public class MainActivity extends Activity {private static final String TAG = MainActivity.class.getSimpleName();private String path = "file:///android_asset/1.mp3";private MediaPlayer mediaPlayer;private TextView text;private Button button;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.main);text = (TextView) findViewById(R.id.text);button = (Button) findViewById(R.id.button);button.setText("Play");button.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {// TODO Auto-generated method stubif (mediaPlayer.isPlaying()) {text.setText("Play pause");mediaPlayer.pause();button.setText("Play");} else {text.setText("Playing");mediaPlayer.start();button.setText("Pause");}}});mediaPlayer = new MediaPlayer();InitMusic(path);mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {@Overridepublic void onCompletion(MediaPlayer mp) {// TODO Auto-generated method stub// ResetMusic(mp3Path);text.setText("Play start");mediaPlayer.start();}});}public void InitMusic(String path) {mediaPlayer.reset();try {AssetFileDescriptor descriptor = getAssets().openFd("1.mp3");mediaPlayer.setDataSource(descriptor.getFileDescriptor());mediaPlayer.prepare();} catch (IllegalArgumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IllegalStateException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} }@Overrideprotected void onDestroy() {if (mediaPlayer != null)mediaPlayer.release();super.onDestroy();}}
main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:orientation="vertical"    tools:context=".MainActivity" >    <TextView        android:id="@+id/text"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" />        <Button        android:id="@+id/button"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></LinearLayout>



0 0
原创粉丝点击