可以使用直接new的方式:
MediaPlayer mp = new MediaPlayer();
也可以使用create的方式,如:
MediaPlayer mp = MediaPlayer.create(this, R.raw.test);//这时就不用调用setDataSource了
MediaPlayer要播放的文件主要包括3个来源:
a. 用户在应用中事先自带的resource资源
例如:MediaPlayer.create(this, R.raw.test);
b. 存储在SD卡或其他文件路径下的媒体文件
例如:mp.setDataSource(“/sdcard/test.mp3”);
c. 网络上的媒体文件
例如:mp.setDataSource(“http://www.citynorth.cn/music/confucius.mp3“);
MediaPlayer的setDataSource一共四个方法:
setDataSource (String path)
setDataSource (FileDescriptor fd)
setDataSource (Context context, Uri uri)
setDataSource (FileDescriptor fd, long offset, long length)
其中使用FileDescriptor时,需要将文件放到与res文件夹平级的assets文件夹里,然后使用:
AssetFileDescriptor fileDescriptor = getAssets().openFd(“rain.mp3”);
m_mediaPlayer.setDataSource(fileDescriptor.getFileDescriptor(),fileDescriptor.getStartOffset(), fileDescriptor.getLength());
来设置datasource
Android通过控制播放器的状态的方式来控制媒体文件的播放,其中:
prepare()和prepareAsync() 提供了同步和异步两种方式设置播放器进入prepare状态,需要注意的是,如果MediaPlayer实例是由create方法创建的,那么第一次启动播放前不需要再调用prepare()了,因为create方法里已经调用过了。
start()是真正启动文件播放的方法,
pause()和stop()比较简单,起到暂停和停止播放的作用,
seekTo()是定位方法,可以让播放器从指定的位置开始播放,需要注意的是该方法是个异步方法,也就是说该方法返回时并不意味着定位完成,尤其是播放的网络文件,真正定位完成时会触发OnSeekComplete.onSeekComplete(),如果需要是可以调用setOnSeekCompleteListener(OnSeekCompleteListener)设置监听器来处理的。
release()可以释放播放器占用的资源,一旦确定不再使用播放器时应当尽早调用它释放资源。
reset()可以使播放器从Error状态中恢复过来,重新会到Idle状态。
MediaPlayer提供了一些设置不同监听器的方法来更好地对播放器的工作状态进行监听,以期及时处理各种情况,
如: setOnCompletionListener(MediaPlayer.OnCompletionListener listener)、
setOnErrorListener(MediaPlayer.OnErrorListener listener)等,设置播放器时需要考虑到播放器可能出现的情况设置好监听和处理逻辑,以保持播放器的健壮性。
只是用MediaPlayer是比较简单的只要按照顺序写就可以了。代码如下:
if (player==null){
player= new MediaPlayer();
}
player.reset();
// String ss= intent.getStringExtra("music");
singer=intent.getIntExtra("music",0);
String ss= paths[singer];
try {
player.setDataSource(ss);//设置打开的文件路径
player.prepare();//准备工作
//如果准备好了
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();//开始播放
play_max= player.getDuration();//获得总时长
Intent intent1 = new Intent("com.play.music");
intent1.putExtra("type",0);
intent1.putExtra("music_time",play_max);
intent1.putExtra("music_name",musics[singer].getName());
sendBroadcast(intent1);
myThread = new MyThread();
myThread.start();
1)建立 MediaPlayer实例( player= new MediaPlayer();)
2)player.reset();
3)player.setDataSource(ss);//设置打开的文件路径
4) player.prepare();//准备工作
5) player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {}
6)在5)的大括号中mp.start();//开始播放
7) player.pause();
8)player.stop( );
音乐播放器的代码如下:
Activity中:
public class MainActivity extends Activity implements View.OnClickListener{
private Button start_button;
public static MainActivity mainActivity = new MainActivity();
private ListView musicListView;
private SeekBar seek_Bar;
private MyReceiver myReceiver;
private TextView max_time;
private TextView day_time;
private Button next_button;
private Button before_button;
private TextView name_music;
File [] musics;
int day_singer;
private boolean zhaungtai=true;
SimpleDateFormat simpleDateFormat =new SimpleDateFormat("mm:ss");
private static final int DESC=0x23;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_button = (Button) findViewById(R.id.start_button);
next_button = (Button) findViewById(R.id.next_music);
musicListView= (ListView) findViewById(R.id.music_list);
seek_Bar= (SeekBar) findViewById(R.id.seek_bar);
max_time= (TextView) findViewById(R.id.max_time);
day_time= (TextView) findViewById(R.id.day_time);
before_button = (Button) findViewById(R.id.before_next_music);
name_music = (TextView) findViewById(R.id.name_music);
start_button.setOnClickListener(this);
next_button.setOnClickListener(this);
before_button.setOnClickListener(this);
//******************************************************
//找到音乐的路径
//*****************************************************
File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
musics = music.listFiles();
String [] paths = new String[musics.length];
for(int i =0 ;i<paths.length;i++){
paths[i]=musics[i].getAbsolutePath();
}
//*********************************************************
MusicAdapter adapter = new MusicAdapter(getLayoutInflater(),musics);
musicListView.setAdapter(adapter);
musicListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
day_singer=position;
intent.putExtra("type",Config.START);
// intent.putExtra("music",musics[position].getAbsolutePath().toString());
intent.putExtra("music",position);
startService(intent);
name_music.setText(musics[position].getName());
}
});
seek_Bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type",Config.SEEKTO);
intent.putExtra("progress",seekBar.getProgress());
startService(intent);
}
});
myReceiver =new MyReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction("com.play.music");
registerReceiver( myReceiver,filter);
}
@Override
protected void onDestroy() {
super.onDestroy();
Log.d("aaaaaaaaaaaaaa","hhhdhd");
unregisterReceiver(myReceiver);
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
switch (v.getId()){
case R.id.start_button:
zhaungtai=!zhaungtai;
if(zhaungtai){
start_button.setBackground(getResources().getDrawable(R.mipmap.play));
intent.putExtra("type",Config.START_ALL);
startService(intent);
}else {
intent.putExtra("type",Config.PAUSE);
startService(intent);
start_button.setBackground(getResources().getDrawable(R.mipmap.pause));
}
break;
case R.id.next_music:
if(day_singer==musics.length-1){
day_singer=-1;
}
Intent intent_next = new Intent(getApplicationContext(),MusicService.class);
int day_singer_next= day_singer+1;
day_singer=day_singer_next;
intent_next.putExtra("type",Config.START);
intent_next.putExtra("music",day_singer_next);
name_music.setText(musics[day_singer_next].getName());
startService(intent_next);
break;
case R.id.before_next_music:
if(day_singer==0){
day_singer=musics.length;
}
Intent intent_bnext = new Intent(getApplicationContext(),MusicService.class);
int day_singer_bnext= day_singer-1;
day_singer=day_singer_bnext;
intent_bnext.putExtra("type",Config.START);
intent_bnext.putExtra("music",day_singer_bnext);
name_music.setText(musics[day_singer_bnext].getName());
startService(intent_bnext);
break;
}
}
class MyReceiver extends BroadcastReceiver{
int max =0;
@Override
public void onReceive(Context context, Intent intent) {
int time_max_day = intent.getIntExtra("music_time",0);
String music_name = intent.getStringExtra("music_name");
String time =simpleDateFormat.format(new Date(intent.getIntExtra("music_time",0)));//时间格式化显示
switch (intent.getIntExtra("type",0)){
case 0:
max=time_max_day;
seek_Bar.setMax(time_max_day);
max_time.setText(time);
name_music.setText(music_name);
break;
case 1:
seek_Bar.setProgress(time_max_day);
day_time.setText(time);
break;
}
MusicAdapter的代码:
public class MusicAdapter extends BaseAdapter {
private LayoutInflater inflater;
File []musics;
public MusicAdapter(LayoutInflater inflater, File[] musics) {
this.inflater = inflater;
this.musics = musics;
}
@Override
public int getCount() {
return musics.length;
}
@Override
public Object getItem(int position) {
return position;
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder vh =null;
if(convertView==null){
vh = new ViewHolder();
convertView=inflater.inflate(R.layout.itemlist,null);
convertView.setTag(vh);
}
vh= (ViewHolder) convertView.getTag();
vh.music_TestView= (TextView) convertView.findViewById(R.id.music_TextView);
vh.imageView_music = (ImageView) convertView.findViewById(R.id.image_music);
vh.author_music = (TextView) convertView.findViewById(R.id.author_textView);
vh.music_TestView.setText(musics[position].getName());
MediaMetadataRetriever mmr = new MediaMetadataRetriever();
mmr.setDataSource(musics[position].getAbsolutePath());//设置绝对路径
String author=mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_ARTIST);//获得作者的名称
if(author!=null){
vh.author_music.setText(author);
}else {
vh.author_music.setText("<未知>");
}
byte[] image = mmr.getEmbeddedPicture();//获得图像的名称
if(image!=null){
Bitmap bitmap = BitmapFactory.decodeByteArray(image,0,image.length);
vh.imageView_music.setImageBitmap(bitmap);
}else {
vh.imageView_music.setImageResource(R.mipmap.ic_launcher);
}
return convertView;
}
class ViewHolder{
TextView music_TestView;
ImageView imageView_music;
TextView author_music;
}
}
MusicService的代码:
public class MusicService extends Service {
Handler handler;
MyThread myThread;
File[] musics;
String [] paths;
int singer;
int play_time;
int play_max;
@Override
public void onCreate() {
super.onCreate();
File music = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);
musics = music.listFiles();
paths = new String[musics.length];
for(int i =0 ;i<paths.length;i++){
paths[i]=musics[i].getAbsolutePath();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
MediaPlayer player;
@Override
public int onStartCommand(final Intent intent, int flags, int startId) {
// handler = new Handler();
int type = intent.getIntExtra("type",0);
switch (type){
case Config.START:
StartMusic(intent);
break;
case Config.SEEKTO:
if(player!=null){
int progress= intent.getIntExtra("progress",0);
player.seekTo(progress);
}
break;
case Config.START_ALL:
player.start();
myThread = new MyThread();
myThread.start();
break;
case Config.PAUSE:
player.pause();
break;
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
private void StartMusic(Intent intent) {
if (player==null){
player= new MediaPlayer();
}
player.reset();
// String ss= intent.getStringExtra("music");
singer=intent.getIntExtra("music",0);
String ss= paths[singer];
try {
player.setDataSource(ss);//设置打开的文件路径
player.prepare();//准备工作
//如果准备好了
player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mp.start();//开始播放
play_max= player.getDuration();//获得总时长
Intent intent1 = new Intent("com.play.music");
intent1.putExtra("type",0);
intent1.putExtra("music_time",play_max);
intent1.putExtra("music_name",musics[singer].getName());
sendBroadcast(intent1);
myThread = new MyThread();
myThread.start();
new Thread(){
@Override
public void run() {
while (play_max>=play_time+1000){
}
singer++;
if(singer==musics.length){
singer=0;
}
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type",Config.START);
intent.putExtra("music",singer);
startService(intent);
}
}.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
class MyThread extends Thread{
@Override
public void run() {
while (player.isPlaying()){
play_time=player.getCurrentPosition();
Intent intent = new Intent("com.play.music");
intent.putExtra("type",1);
intent.putExtra("music_time",play_time);
sendBroadcast(intent);
}
}
}
}
在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" tools:context=".MainActivity" android:orientation="vertical" >
<TextView android:id="@+id/name_music" android:layout_width="100dp" android:layout_height="wrap_content" android:layout_marginLeft="130dp" android:lines="1" android:ellipsize="marquee" android:singleLine="true" android:focusable="true" android:focusableInTouchMode="true" android:textColor="#ff0000" android:textSize="30dp" android:text="欢迎进入我的音乐宝库" />
<ListView android:id="@+id/music_list" android:layout_width="match_parent" android:layout_height="0dp" android:layout_weight="1" ></ListView>
<SeekBar android:id="@+id/seek_bar" android:layout_width="match_parent" android:layout_height="wrap_content" />
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" >
<TextView android:id="@+id/day_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50dp" />
<TextView android:id="@+id/max_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="200dp" />
</LinearLayout>
<LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="horizontal" android:layout_gravity="center" >
<Button android:layout_marginLeft="90dp" android:id="@+id/before_next_music" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@mipmap/shang" />
<Button android:id="@+id/start_button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@mipmap/play" />
<Button android:id="@+id/next_music" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@mipmap/xia" />
</LinearLayout>
</LinearLayout>
注意:在mainfests中声明权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
seekBar是一种可以拖动的进度条。
在上面的代码中就可以看到他的身影,在XML中:
<SeekBar android:id="@+id/seek_bar" android:layout_width="match_parent" android:layout_height="wrap_content" />
在代码中可以利用: seek_Bar.setProgress(int params);设置所在的位置。seekBar.getProgress());获得所在的位置。可以利用下面的代码,在手动滑动时获得所滑动的位置:
seek_Bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
Intent intent = new Intent(getApplicationContext(),MusicService.class);
intent.putExtra("type",Config.SEEKTO);
intent.putExtra("progress",seekBar.getProgress());
startService(intent);
}
});