天天看點

Android 音樂播放器的實作

本文章将一步一步實作Android 音樂播放器,利用Android強大的API,可以很友善的制作自己風格的音樂播放器。利用本文介紹的例子,實作音樂播放器的關鍵代碼,如果再加上自己的UI設計定制方案,就可以做出自己想要的播放器了。

首先我們寫一個xml的界面布局,這裡用一個listview來展示音樂清單,并提供簡單的音樂播放控制按鈕和一個可以拖拽的進度條來控制音量的大小。

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/back"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/listView1"
        android:listSelector="#fef"
		android:drawSelectorOnTop="false"        
        android:layout_weight="1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </ListView>

    <LinearLayout
        android:layout_width="match_parent"
        android:orientation="vertical"
        android:layout_height="wrap_content" >

        <SeekBar
            android:id="@+id/seekBar"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_weight="1" />

        <RelativeLayout
            android:layout_width="fill_parent"
            android:layout_height="fill_parent" >

            <Button
                android:id="@+id/next"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentRight="true"
                android:layout_alignParentTop="true"
                android:text="下一曲" />

            <Button
                android:id="@+id/pre"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentLeft="true"
                android:layout_alignParentTop="true"
                android:text="上一曲" />

            <Button
                android:id="@+id/pause"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_marginLeft="16dp"
                android:layout_toRightOf="@+id/pre"
                android:text="播放" />

            <Button
                android:id="@+id/stop"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_alignParentTop="true"
                android:layout_toLeftOf="@+id/next"
                android:text="停止" />

        </RelativeLayout>

    </LinearLayout>

</LinearLayout>
           

然後編寫我們的Activity主程式,首先初始化一個mediaPlayer,并設定各個按鈕的初始化

<span style="white-space:pre">	</span>mediaPlayer = new MediaPlayer();
        Button next = (Button) findViewById(R.id.next);
        pause = (Button) findViewById(R.id.pause);
        Button pre = (Button) findViewById(R.id.pre);
        Button stop = (Button) findViewById(R.id.stop);
        audioList();
        mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
			
			@Override
			public void onCompletion(MediaPlayer mp) {
				nextMusic();
			}
		});
        stop.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mediaPlayer.isPlaying()){
					mediaPlayer.stop();
				}
				pause.setText("開始");
			}
		});
        pause.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if(mediaPlayer.isPlaying()){
					mediaPlayer.pause();
					((Button)v).setText("繼續");
				}else{
					mediaPlayer.start();
					((Button)v).setText("暫停");
					
				}
			}
		});
        next.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				nextMusic();
			}
		});
        pre.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				preMusic();
			}
		});
           

音樂清單我們可以通過周遊sd卡總所有音樂檔案,擷取裝置存儲的所有音樂,展示在我們的清單中。不過這樣會比較耗時,可以将音樂放在某一檔案中,然後修改getFiles方法,擷取此路徑下的音樂

<span style="white-space:pre">	</span>private void audioList() {
		getFiles(Environment.getExternalStorageDirectory().getPath());
		ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
				android.R.layout.simple_list_item_1,audioList);
		ListView listView = (ListView) findViewById(R.id.listView1);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> viewList, View view, 
					int position,long id) {
				currentItem = position;
				String path = map.get(audioList.get(position));
				playMusic(path);
			}
		});
	}
           
<span style="white-space:pre">	</span>private void getFiles(String path) {
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>File files = new File(path);
<span style="white-space:pre">		</span>File[] file = files.listFiles();
<span style="white-space:pre">		</span>
<span style="white-space:pre">		</span>try {
<span style="white-space:pre">			</span>for (File f : file) {
<span style="white-space:pre">				</span>if(f.isDirectory()){
<span style="white-space:pre">					</span>getFiles(f.getAbsolutePath());
<span style="white-space:pre">				</span>}else{
<span style="white-space:pre">					</span>if(f.length()>512)
<span style="white-space:pre">						</span>
<span style="white-space:pre">					</span>if(isAudioFile(f.getPath())){
<span style="white-space:pre">						</span>audioList.add(f.getPath().substring(f.getPath().lastIndexOf("/")+1));
<span style="white-space:pre">						</span>map.put(f.getPath().substring(f.getPath().lastIndexOf("/")+1), f.getPath());
<span style="white-space:pre">					</span>}
<span style="white-space:pre">				</span>}
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>} catch (Exception e) {
<span style="white-space:pre">			</span>e.printStackTrace();
<span style="white-space:pre">		</span>}
<span style="white-space:pre">	</span>}
           

判斷是否是音樂檔案,可以通過檔案的擴充名,此處我們暫時隻搜尋3種類型的音樂

<span style="white-space:pre">	</span>private static String[] imageFormatSet = new String[]{"ape", "mp3", "wav" };
<span style="white-space:pre">	</span>private boolean isAudioFile(String path) {
<span style="white-space:pre">		</span> // 擷取擴充名
<span style="white-space:pre">		</span> String FileEnd = path.substring(path.lastIndexOf(".") + 1,
<span style="white-space:pre">				</span> path.length()).toLowerCase();
<span style="white-space:pre">		</span>for(String format:imageFormatSet){
<span style="white-space:pre">			</span>if(FileEnd.equals(format)){
<span style="white-space:pre">				</span>return true;
<span style="white-space:pre">			</span>}
<span style="white-space:pre">		</span>}
<span style="white-space:pre">		</span>return false;
<span style="white-space:pre">	</span>}
           

下面是最關鍵的音樂播放和相關按鈕的實作

protected void playMusic(String path) {
		
		try {
			if(mediaPlayer.isPlaying()){
				mediaPlayer.stop();
			}
			mediaPlayer.reset();
			mediaPlayer.setDataSource(path);
			mediaPlayer.prepare();
			mediaPlayer.start();
			pause.setText("暫停");
			pause.setEnabled(true);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
<span style="white-space:pre">	</span>protected void nextMusic() {
		if(++currentItem >= audioList.size()){
			currentItem = 0;
		}

		String path = map.get(audioList.get(currentItem));
		playMusic(path);
	}
	protected void preMusic() {
		if(--currentItem >= 0){
			if(currentItem >= audioList.size()){
				currentItem = 0;
			}
		}else{
			currentItem = audioList.size() - 1;
		}
		String path = map.get(audioList.get(currentItem));
		playMusic(path);
	}
           

最後,還有音樂播放時拖動進度條改變音量大小的實作。

<span style="white-space:pre">	</span>final AudioManager am = (AudioManager) MainActivity.this.getSystemService(Context.AUDIO_SERVICE);
        MainActivity.this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        SeekBar seekBar = (SeekBar) findViewById(R.id.seekBar);
        seekBar.setMax(am.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
        int progress = am.getStreamVolume(AudioManager.STREAM_MUSIC);
        seekBar.setProgress(progress);
        seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
			
			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				
			}
			
			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				am.setStreamVolume(AudioManager.STREAM_MUSIC, progress, AudioManager.FLAG_PLAY_SOUND);
			}
		});
           

至此,我們的簡易音樂播放器就實作了。最後不要忘了在AndroidManifest.xml中添加對外部存儲的通路權限

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
           

是不是很容易,也很振奮人心。

動手制作你自己的播放器吧。