Android(安卓)播放mp3
写一个小程序,在App里面实现mp3的播发,暂停,停止
步骤:
1. 新建项目,添加mp3
2. UI 制作 activity_main.xml添加3个按钮,实现播放,暂停,停止
android:layout_height="fill_parent"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:contentDescription="@string/app_name"
android:layout_gravity="center"
android:src="@drawable/ic_launcher" />
android:layout_height="wrap_content" >
3 MainActivity.class 添加3个按钮的监控器
package com.example.hello;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private Button start;
private Button pause;
private Button stop;
private MediaPlayer player;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = (Button)findViewById(R.id.start);
pause = (Button)findViewById(R.id.pause);
stop = (Button)findViewById(R.id.stop);
NewListener newListener = new NewListener();
start.setOnClickListener(newListener);
pause.setOnClickListener(newListener);
stop.setOnClickListener(newListener);
//MediaPlayer初始化
player = MediaPlayer.create(this, R.raw.test);
}
class NewListener implements OnClickListener{
@Override
public void onClick(View v){
switch (v.getId()) {
case R.id.start:{
//不播发就播发
if(!player.isPlaying()){
player.start();
}
break;
}
case R.id.pause:{
if(player.isPlaying()){
player.pause();
}
}
case R.id.stop:{
if(player.isPlaying()){
player.stop();
}
}
}
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onDestroy(){
super.onDestroy();
if(player != null){
player.release();
}
}
}
这个小程序还没有实现后台播放音乐,还应该添加service
更多相关文章
- Android(安卓)实现全屏显示的几种方法整理
- Android不依赖Activity的全局悬浮窗实现
- Android不依赖Activity的全局悬浮窗实现
- android之照相、相冊裁剪功能的实现过程
- 实现Android包的批量删除
- android 5.0多用户支持
- Android(安卓)选择器 PickerView实例,时间选择器、地址选择器、单
- 简单实现Android顶部工具栏和底部工具栏(原创)
- 选项卡使用方法二(Android学习随笔十三)