简略的音频播放示例
简单的音频播放示例
简单的音乐播放示例
Mainactivity.java中的代码:
public class MainActivity extends Activity implements OnClickListener { //实例化一个名为mp的播放对象 MediaPlayer mp=null; //声明视图控件对象;bt1,bt2,bt3; View bt1=null; View bt2=null; View bt3=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //主界面的视图 setContentView(R.layout.activity_main); //将视图控件与视图对象关联 View bt1=(View)findViewById(R.id.button1); View bt2=(View)findViewById(R.id.button2); View bt3=(View)findViewById(R.id.button3); bt1.setOnClickListener(this); bt2.setOnClickListener(this); bt3.setOnClickListener(this);}
//各个bt监听的事件 @Override public void onClick(View v) { //getId()获取id switch(v.getId()){ case R.id.button1: //Toast是bt点击后屏幕下方一闪的提示框 Toast.makeText(this, R.string.from_project, Toast.LENGTH_LONG).show(); if(mp!=null){ //停止当前正在播放的音频 mp.stop(); } //音乐的名称一定一定要规范 mp=MediaPlayer.create(this, R.raw.alin ); //开始播放 mp.start(); break; case R.id.button2: Toast.makeText(this, R.string.from_file, Toast.LENGTH_LONG).show(); if(mp!=null){ mp.stop(); } //创建播放对象 mp=new MediaPlayer(); String path="/sdcard/love.mp3"; try { //设置数据源 mp.setDataSource(path); //准备 mp.prepare(); mp.start(); } catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SecurityException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalStateException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } break; case R.id.button3: Toast.makeText(this, R.string.from_internet, Toast.LENGTH_LONG).show(); if(mp!=null){ mp.stop(); }
activity_main.xml中的代码:
<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_centerHorizontal="true" android:layout_marginTop="14dp" android:text="@string/musicdemo" /> <Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/textView1" android:layout_centerHorizontal="true" android:layout_marginTop="38dp" android:text="@string/from_project" /> <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:layout_marginTop="30dp" android:text="@string/from_file" /> <Button android:id="@+id/button3" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_below="@+id/button2" android:layout_centerHorizontal="true" android:layout_marginTop="28dp" android:text="@string/from_internet" />