Android編程實現播放MP3功能示例
本文實例講述了Android編程實現播放MP3功能。分享給大家供大家參考,具體如下:
在android中播放mp3非常簡單,也是項目中經常使用的,比如說要做項目的背景音樂,應用中某些功能的提示音等的。應用非常廣泛,下面提供一個簡單的使用實例:
layout文件的配置:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:orientation="vertical"
android:layout_height="wrap_content">
<Button android:text="播放" android:id="@+id/btnStart"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
<Button android:text="停止" android:id="@+id/btnStop"
android:layout_width="fill_parent" android:layout_height="wrap_content">
</Button>
</LinearLayout>
java實現文件:
/**
*
*/
package com.demo.media;
import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import com.demo.HelloWorld.R;
/**
* @author xsl
* vaiyanzi@gmail.com
* 實現MP3播放功能
*/
public class mediademo extends Activity {
private Button btnStart,btnStop;
private static MediaPlayer mediaPlayer=null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.media);
btnStart = (Button) this.findViewById(R.id.btnStart);
btnStart.setOnClickListener(new ButtonListener());
btnStop = (Button) this.findViewById(R.id.btnStop);
btnStop.setOnClickListener(new ButtonListener());
}
class ButtonListener implements OnClickListener{
public void onClick(View v) {
switch(v.getId()){
case R.id.btnStart:
if(mediaPlayer==null){
//創(chuàng)建播放實例
mediaPlayer=MediaPlayer.create(mediademo.this, R.raw.tishiyin);
}
try {
//設置是否循環(huán)播放
mediaPlayer.setLooping(true);
//設置播放起始點
mediaPlayer.seekTo(0);
//開始播放
mediaPlayer.start();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
break;
case R.id.btnStop:
if(mediaPlayer!=null){
//停止播放
mediaPlayer.stop();
//釋放資源
mediaPlayer.release();
mediaPlayer=null;
}
break;
}
}
}
}
效果如圖:

更多關于Android相關內容感興趣的讀者可查看本站專題:《Android多媒體操作技巧匯總(音頻,視頻,錄音等)》、《Android Service組件使用技巧總結》、《Android編程之activity操作技巧總結》、《Android資源操作技巧匯總》、《Android文件操作技巧匯總》、《Android開發(fā)入門與進階教程》、《Android視圖View技巧總結》及《Android控件用法總結》
希望本文所述對大家Android程序設計有所幫助。
相關文章
Android開發(fā)判斷一個app應用是否在運行的方法詳解
這篇文章主要介紹了Android開發(fā)判斷一個app應用是否在運行的方法,結合實例形式較為詳細的分析了Android判斷應用運行狀態(tài)的相關操作技巧與注意事項,需要的朋友可以參考下2017-11-11
在Android中創(chuàng)建菜單項Menu以及獲取手機分辨率的解決方法
本篇文章小編為大家介紹,在Android中創(chuàng)建菜單項Menu以及獲取手機分辨率的解決方法。需要的朋友參考下2013-04-04
Android xUtils更新到3.0后的基本使用規(guī)則詳解
xUtils是基于android的開發(fā)框架,簡化了很多的開發(fā)步驟,可以說是非常好的開發(fā)工具。下面小編給大家?guī)砹薃ndroid xUtils更新到3.0后的基本使用規(guī)則詳解,感興趣的朋友一起學習吧2016-08-08

