android 简单的音乐播放器
生活随笔
收集整理的這篇文章主要介紹了
android 简单的音乐播放器
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
? ? ? ?在項(xiàng)目開(kāi)發(fā)過(guò)程中需要一個(gè)簡(jiǎn)單的音頻播放的功能,需求很簡(jiǎn)單,只需要能夠播放一個(gè)指定文件夾的全部mp3和wav音頻文件就可以,谷歌給我們提供了一套比較完整的API,使得我們可以很簡(jiǎn)單的寫出一個(gè)簡(jiǎn)易的音樂(lè)播放器,在android中播放音頻文件一般都是使用MediaPlayer類來(lái)實(shí)現(xiàn),這個(gè)播放器中我們需要有暫停、停止、上一首、下一首等基本按鈕。
首先設(shè)計(jì)一個(gè)簡(jiǎn)單的音樂(lè)播放界面
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:id="@+id/updatevedio"android:layout_width="wrap_content"android:layout_height="wrap_content"android:textSize="30sp"android:text="音樂(lè)列表"/> <ListViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_below="@id/updatevedio"android:id="@+id/lv"></ListView> <TextView android:id="@+id/name"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentBottom="true"android:layout_alignParentLeft="true"android:maxEms="8" android:singleLine="true"android:ellipsize="marquee"android:paddingBottom="20dp"android:textSize="20sp"/> <LinearLayout android:id="@+id/linearLayout"android:layout_alignParentBottom="true"android:layout_centerInParent="true"android:layout_width="wrap_content"android:layout_height="wrap_content"android:orientation="horizontal"><Button android:id="@+id/model"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/xunhuan"/><Button android:id="@+id/back"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/shangyishou"/><Button android:id="@+id/pause"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/zanting"/><Button android:id="@+id/next"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@drawable/xiayishou"/></LinearLayout><SeekBar android:id="@+id/seekBar"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_above="@id/linearLayout"/></RelativeLayout>界面很簡(jiǎn)單,也就不多說(shuō)了
在activity中實(shí)現(xiàn)功能。
首先獲得xml文件中的控件
lv = (ListView) findViewById(R.id.lv); seekBar = (SeekBar) findViewById(R.id.seekBar);modelButton = (Button) findViewById(R.id.model);backButton = (Button) findViewById(R.id.back);pauseButton = (Button) findViewById(R.id.pause);nextButton = (Button) findViewById(R.id.next);nameText = (TextView) findViewById(R.id.name);綁定監(jiān)聽(tīng)器
pauseButton.setOnClickListener(this);backButton.setOnClickListener(this);modelButton.setOnClickListener(this);nextButton.setOnClickListener(this);//進(jìn)度條監(jiān)聽(tīng)器 seekBar.setOnSeekBarChangeListener(new MySeekBarListener()); 掃描一個(gè)文件加內(nèi)所有的音頻文件
//獲得視頻列表private void mp3List(){ if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { // File path = Environment.getExternalStorageDirectory();// 獲得SD卡路徑 System.out.println("path-------》" + path);//File[] files = path.listFiles();// 讀取 String musicPath = path + "/Music"; getFileName(musicPath); //視頻列表Log.i(LOG, musicPath);} SimpleAdapter adapter = new SimpleAdapter(this, musicList, R.layout.sd_list, new String[] { "name" }, new int[] { R.id.mp4 }); lv.setAdapter(adapter);for (int i = 0; i < musicList.size(); i++) { Log.i(LOG, "list. name: " + musicList.get(i)); }lv.setOnItemClickListener(new ListView.OnItemClickListener(){@Overridepublic void onItemClick(AdapterView<?> arg0, View view, int position,long id) { songNum = position;initMediaPlayer(songNum);} }); }//僅搜索當(dāng)前目錄下的文件 private void getFileName(String url) { File files = new File(url);File[] file = files.listFiles();//先判斷目錄是否為空,否則會(huì)報(bào)空指針if (files != null) { for (File f : file) { String fileName = f.getName(); if (fileName.endsWith(".mp3")||fileName.endsWith(".wav")) { HashMap<String, String> map = new HashMap<String, String>(); String s = fileName.substring(0,fileName.lastIndexOf(".")).toString(); //獲取文件的地址musicpath = f.getPath();Log.i(LOG, "文件名mp3或wav:: " + s); map.put("name", fileName);// map.put("mp3", f.getName()); System.out.println("1111111---" + fileName);musicpathlist.add(musicpath);musicList.add(map); } } } }這里在根目錄的Music文件夾下面放了幾首個(gè),然后查詢后綴為.mp3和.wav的音頻文件添加到listView中。在adapter中還用到了一個(gè)sd_list布局,代碼如下:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical" ><TextViewandroid:layout_width="match_parent"android:layout_height="wrap_content"android:textSize="30sp"android:id="@+id/mp4"/> </LinearLayout> 得到音頻的列表之后就是使用mediaPlayer對(duì)音頻進(jìn)行播放, mediaPlayer提供了很多方法可以讓開(kāi)發(fā)者直接調(diào)用。
為L(zhǎng)istView綁定監(jiān)控
private void initMediaPlayer(int songNum){musicname = musicpathlist.get(songNum); Log.i(LOG, musicname);if (musicname != null) {try {mediaPlayer.reset(); //重置多媒體 //指定音頻文件地址mediaPlayer.setDataSource(musicname);//這是一個(gè)地址String path = musicpathlist.get(songNum);String Text[] = path.split("/");Log.i(LOG, Text[5]);//設(shè)置當(dāng)前播放文件nameText.setText(Text[Text.length - 1]);Log.i(LOG, "播放");//準(zhǔn)備播放mediaPlayer.prepare();start(); // if (!mediaPlayer.isPlaying()) { // mediaPlayer.start(); // System.out.println("開(kāi)始播放"); // }} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}實(shí)現(xiàn)暫停,下一首,上一首等功能
public void start() { try { mediaPlayer.start();//開(kāi)始播放 //設(shè)置進(jìn)度條長(zhǎng)度 seekBar.setMax(mediaPlayer.getDuration()); //發(fā)送一個(gè)Runnable, handler收到之后就會(huì)執(zhí)行run()方法 handler.post(new Runnable() { public void run() { // 更新進(jìn)度條狀態(tài) if (!isStartTrackingTouch) //獲取當(dāng)前播放音樂(lè)的位置seekBar.setProgress(mediaPlayer.getCurrentPosition()); // 1秒之后再次發(fā)送 handler.postDelayed(this, 1000); } });//setOnCompletionListener 當(dāng)當(dāng)前多媒體對(duì)象播放完成時(shí)發(fā)生的事件 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer arg0) { next();//如果當(dāng)前歌曲播放完畢,自動(dòng)播放下一首. } }); } catch (Exception e) { Log.v("MusicService", e.getMessage()); } } public void next() { Toast.makeText(getApplicationContext(), "下一首", Toast.LENGTH_SHORT).show();songNum = songNum == musicList.size() - 1 ? 0 : songNum + 1; initMediaPlayer(songNum); } public void back() { Toast.makeText(getApplicationContext(), "上一首", Toast.LENGTH_SHORT).show();//songNum = songNum == 0 ? musicList.size() - 1 : songNum - 1; songNum = songNum - 1 < 0 ? musicList.size() - 1 : songNum - 1; initMediaPlayer(songNum); } public void pause() { if (mediaPlayer.isPlaying()) {pauseButton.setBackgroundResource(R.drawable.zanting);mediaPlayer.pause(); }else mediaPlayer.start(); } public void stop() { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); } } 程序的最后要釋放mediaPlayer占用的資源
protected void onDestroy() {// TODO Auto-generated method stubsuper.onDestroy();if (mediaPlayer != null) {mediaPlayer.stop();//mediaPlayer.release();}}這樣一個(gè)簡(jiǎn)易的音頻播放器就實(shí)現(xiàn)了。
這是一個(gè)非常簡(jiǎn)單的音樂(lè)播放器,在設(shè)計(jì)中沒(méi)有使用Service實(shí)現(xiàn)后臺(tái)播放,切換播放模式也還沒(méi)有實(shí)現(xiàn),但是對(duì)于在現(xiàn)在手上的項(xiàng)目來(lái)說(shuō)已經(jīng)夠了,后續(xù)的工作慢慢在實(shí)現(xiàn)。
最后附上代碼。。。
點(diǎn)擊打開(kāi)鏈接
總結(jié)
以上是生活随笔為你收集整理的android 简单的音乐播放器的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 帕萨特价格多少 了解帕萨特的市场行情和价
- 下一篇: android ListView适配器