扣丁学堂笔记第22天多媒体播放
1.简单介绍与播放三种媒体源
MainActivity
package com.example.mediaplayertest; import java.io.IOException; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.view.Menu; import android.view.MenuItem; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void playResClick(View view) { // MediaPlayer mp = MediaPlayer.create(this, R.raw.a1); // mp.start(); } public void playSysClick(View view) { MediaPlayer mp = new MediaPlayer(); String path = Environment .getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) + "/a2.mp3"; try { mp.setDataSource(this, Uri.parse(path)); mp.prepare();// 同步运行 mp.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } public void playNetClick(View view) { // 音乐链接要保证有效 String path = "http://y.qq.com/index.html#type=song&mid=0040E7kG0ZJ9al&tpl=yqq_song_detail"; MediaPlayer mp = new MediaPlayer(); try { mp.setDataSource(this, Uri.parse(path)); mp.setOnPreparedListener(new OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } }); mp.prepareAsync(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
activtiy_main
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.mediaplayertest.MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentRight="true" android:layout_alignParentTop="true" android:text="播放本地文件" android:onClick="playResClick" /> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignRight="@+id/button1" android:layout_below="@+id/button1" android:text="播放系统文件" android:onClick="playSysClick"/> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button2" android:layout_alignRight="@+id/button2" android:layout_below="@+id/button2" android:text="播放网络文件" android:onClick="playNetClick" /> </RelativeLayout>
AndroidManifest
<uses-permission android:name="android.permission.INTERNET"/>
2.MediaPlayer状态分析
3.简单的播放器实现案例
MainActivity
package com.example.simpleplayertest; import java.io.File; import java.io.IOException; import java.util.ArrayList; import android.app.Activity; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.os.Bundle; import android.os.Environment; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class MainActivity extends Activity implements OnClickListener, OnPreparedListener, OnErrorListener, OnCompletionListener { private MediaPlayer player; private int index = 0;//表示当前要播放的音乐的索引 private ArrayList<String> musicList = new ArrayList<String>(); private Button btn_play, btn_pause, btn_last, btn_next; private boolean isPause = false;//true表示暂停状态 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); initView(); initMusic(); player = new MediaPlayer(); player.setOnPreparedListener(this); player.setOnErrorListener(this); player.setOnCompletionListener(this); } private void initView() { // TODO Auto-generated method stub btn_play = (Button) findViewById(R.id.btn_play); btn_pause = (Button) findViewById(R.id.btn_pause); btn_last = (Button) findViewById(R.id.btn_last); btn_next = (Button) findViewById(R.id.btn_next); btn_play.setOnClickListener(this); btn_pause.setOnClickListener(this); btn_last.setOnClickListener(this); btn_next.setOnClickListener(this); } private void initMusic() { String root = Environment.getExternalStoragePublicDirectory( Environment.DIRECTORY_MUSIC).getPath(); musicList.add(root + File.separator + "a.mp3"); musicList.add(root + File.separator + "b.mp3"); musicList.add(root + File.separator + "c.mp3"); musicList.add(root + File.separator + "d.mp3"); } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if(player!=null){ if(player.isPlaying()){ player.stop(); } player.release(); } } @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub next(); } @Override public boolean onError(MediaPlayer mp, int what, int extra) { // TODO Auto-generated method stub player.reset(); return true; } @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } @Override public void onClick(View v) { // TODO Auto-generated method stub switch (v.getId()) { case R.id.btn_play: play(); break; case R.id.btn_pause: pause(); break; case R.id.btn_last: last(); break; case R.id.btn_next: next(); break; default: break; } } private void next() { // TODO Auto-generated method stub if(index+1<musicList.size()-1){ index++; }else{ index = 0; } start(); } private void last() { // TODO Auto-generated method stub if(index-1>=0){ index--; }else{ index = musicList.size()-1; } start(); } //暂停 private void pause() { // TODO Auto-generated method stub if(player.isPlaying()){ player.pause(); isPause = true; } } private void play() { // TODO Auto-generated method stub if(isPause){ player.start();//接着播放(不是从头開始) isPause = false; }else{ start();//音乐从头開始播放的方法 } } //音乐从头開始播放的方法 private void start() { // TODO Auto-generated method stub if(index<musicList.size()){ if(player.isPlaying()){ player.stop(); } player.reset(); String musicPath = musicList.get(index); try { player.setDataSource(musicPath); player.prepareAsync();//之后调用onPrepared方法 isPause = false; }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } }
activity_main
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.simpleplayertest.MainActivity" > <ImageView android:id="@+id/imageView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:src="@drawable/ic_launcher" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/imageView1" android:orientation="horizontal" > <Button android:id="@+id/btn_last" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="上一首" android:layout_weight="1" /> <Button android:id="@+id/btn_play" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBottom="@+id/button1" android:layout_toRightOf="@+id/button1" android:text="播放" android:layout_weight="1"/> <Button android:id="@+id/btn_pause" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button2" android:layout_alignBottom="@+id/button2" android:layout_toRightOf="@+id/button2" android:text="暂停" android:layout_weight="1"/> <Button android:id="@+id/btn_next" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignBaseline="@+id/button3" android:layout_alignBottom="@+id/button3" android:layout_alignParentRight="true" android:text="下一首" android:layout_weight="1"/> </LinearLayout> </RelativeLayout>
4.在服务中使用MediaPlayer
5.作为前台服务执行
在服务中使用mediaplayer+作为前台服务执行代码
MyService.java
package com.example.servicemediaplayertest; import java.io.File; import java.io.IOException; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.Notification.Builder; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.media.MediaPlayer.OnPreparedListener; import android.net.wifi.WifiManager; import android.os.Environment; import android.os.IBinder; import android.os.PowerManager; public class MyService extends Service implements OnPreparedListener{ public static final String ACTION_PLAY = "com.example.servicemediaplayertest.ACTION_PLAY"; public static final String ACTION_PAUSE = "com.example.servicemediaplayertest.ACTION_PAUSE"; public static final String ACTION_EXIT = "com.example.servicemediaplayertest.ACTION_EXIT"; private MediaPlayer player; private WifiManager.WifiLock lock; @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); player = new MediaPlayer(); //保持cpu正常工作 player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); //保持wifi不被休眠 WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE); lock = wifiManager.createWifiLock("myLock"); lock.acquire(); player.setOnPreparedListener(this); notification(); } private void notification() { // TODO Auto-generated method stub Notification.Builder builder = new Builder(this); builder.setTicker("为她音悦"); builder.setSmallIcon(R.drawable.ic_launcher); builder.setContentTitle("我的音乐播放器"); builder.setContentInfo("正在播放"); PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT); builder.setContentIntent(pi); NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); Notification notification = builder.build(); startForeground(0, notification); nm.notify(0,notification); } @Override public int onStartCommand(Intent intent, int flags, int startId) { // TODO Auto-generated method stub String action = intent.getAction(); if(ACTION_PLAY.equals(action)){ player.reset(); try { player.setDataSource(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)+File.separator+"a.mp3"); player.prepareAsync(); }catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if(ACTION_PAUSE.equals(action)){ if(player.isPlaying())player.pause(); }else if(ACTION_EXIT.equals(action)){ if(player.isPlaying())player.stop(); player.release(); } return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); stopForeground(true); lock.release(); } @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onPrepared(MediaPlayer mp) { // TODO Auto-generated method stub mp.start(); } }
MainActivity
package com.example.servicemediaplayertest; import android.app.Activity; import android.app.Notification; import android.app.Notification.Builder; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.view.KeyEvent; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } // @Override // public boolean onKeyDown(int keyCode, KeyEvent event) { // // TODO Auto-generated method stub // if(keyCode==KeyEvent.KEYCODE_BACK){ // // } // return super.onKeyDown(keyCode, event); // } public void playClick(View view) { Intent intent = new Intent(MyService.ACTION_PLAY); startService(intent); } public void pauseClick(View view) { Intent intent = new Intent(MyService.ACTION_PAUSE); startService(intent); } public void exitClick(View view) { Intent intent = new Intent(MyService.ACTION_EXIT); startService(intent); } }
activity_main
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context="com.example.servicemediaplayertest.MainActivity" > <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentLeft="true" android:layout_alignParentTop="true" android:text="PLAY" android:onClick="playClick"/> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button1" android:layout_below="@+id/button1" android:text="PAUSE" android:onClick="pauseClick"/> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignLeft="@+id/button2" android:layout_below="@+id/button2" android:text="EXIT" android:onClick="exitClick"/> </RelativeLayout>
Androidmanifest
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".MyService" android:process=":music"> <intent-filter> <action android:name="com.example.servicemediaplayertest.ACTION_PLAY"/> <action android:name="com.example.servicemediaplayertest.ACTION_PAUSE"/> <action android:name="com.example.servicemediaplayertest.ACTION_EXIT"/> </intent-filter> </service>
6.处理音频焦点
7.ContentResolver获取媒体信息
8.ContentResolver測试