android 简单的音乐播放器
生活随笔
收集整理的這篇文章主要介紹了
android 简单的音乐播放器
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
? ? ? ?在項目開發過程中需要一個簡單的音頻播放的功能,需求很簡單,只需要能夠播放一個指定文件夾的全部mp3和wav音頻文件就可以,谷歌給我們提供了一套比較完整的API,使得我們可以很簡單的寫出一個簡易的音樂播放器,在android中播放音頻文件一般都是使用MediaPlayer類來實現,這個播放器中我們需要有暫停、停止、上一首、下一首等基本按鈕。
首先設計一個簡單的音樂播放界面
<?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="音樂列表"/> <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>界面很簡單,也就不多說了
在activity中實現功能。
首先獲得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);綁定監聽器
pauseButton.setOnClickListener(this);backButton.setOnClickListener(this);modelButton.setOnClickListener(this);nextButton.setOnClickListener(this);//進度條監聽器 seekBar.setOnSeekBarChangeListener(new MySeekBarListener()); 掃描一個文件加內所有的音頻文件
//獲得視頻列表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);} }); }//僅搜索當前目錄下的文件 private void getFileName(String url) { File files = new File(url);File[] file = files.listFiles();//先判斷目錄是否為空,否則會報空指針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文件夾下面放了幾首個,然后查詢后綴為.mp3和.wav的音頻文件添加到listView中。在adapter中還用到了一個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對音頻進行播放, mediaPlayer提供了很多方法可以讓開發者直接調用。
為ListView綁定監控
private void initMediaPlayer(int songNum){musicname = musicpathlist.get(songNum); Log.i(LOG, musicname);if (musicname != null) {try {mediaPlayer.reset(); //重置多媒體 //指定音頻文件地址mediaPlayer.setDataSource(musicname);//這是一個地址String path = musicpathlist.get(songNum);String Text[] = path.split("/");Log.i(LOG, Text[5]);//設置當前播放文件nameText.setText(Text[Text.length - 1]);Log.i(LOG, "播放");//準備播放mediaPlayer.prepare();start(); // if (!mediaPlayer.isPlaying()) { // mediaPlayer.start(); // System.out.println("開始播放"); // }} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}實現暫停,下一首,上一首等功能
public void start() { try { mediaPlayer.start();//開始播放 //設置進度條長度 seekBar.setMax(mediaPlayer.getDuration()); //發送一個Runnable, handler收到之后就會執行run()方法 handler.post(new Runnable() { public void run() { // 更新進度條狀態 if (!isStartTrackingTouch) //獲取當前播放音樂的位置seekBar.setProgress(mediaPlayer.getCurrentPosition()); // 1秒之后再次發送 handler.postDelayed(this, 1000); } });//setOnCompletionListener 當當前多媒體對象播放完成時發生的事件 mediaPlayer.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer arg0) { next();//如果當前歌曲播放完畢,自動播放下一首. } }); } 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();}}這樣一個簡易的音頻播放器就實現了。
這是一個非常簡單的音樂播放器,在設計中沒有使用Service實現后臺播放,切換播放模式也還沒有實現,但是對于在現在手上的項目來說已經夠了,后續的工作慢慢在實現。
最后附上代碼。。。
點擊打開鏈接
總結
以上是生活随笔為你收集整理的android 简单的音乐播放器的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 帕萨特价格多少 了解帕萨特的市场行情和价
- 下一篇: android ListView适配器