Android新手入手教程 -1.使用MediaPlayer播放声音
16lz
2021-01-23
1.引入声音文件
2.布局文件
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/textView" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="没有播放任何声音" /> <Button android:id="@+id/button1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="使用MediaPlayer播放声音" /> <Button android:id="@+id/button2" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="暂停MediaPlayer播放声音" /> <Button android:id="@+id/button3" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="停止MediaPlayer播放声音" />LinearLayout>
3.java代码
package jinny.sqlstudy.project;import android.app.Activity;//引入Activity类import android.media.MediaPlayer;//引入MediaPlayer类import android.os.Bundle;//引入Bundle类import android.view.View;//引入View类import android.view.View.OnClickListener;//引入OnClickListener类import android.widget.Button;//引入Button类import android.widget.TextView;//引入TextView类public class SQLStudyActivity extends Activity implements OnClickListener{ Button button1; Button button2; Button button3; Button button4; TextView textView; MediaPlayer mMediaPlayer; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState){//重写的onCreate回调方法 super.onCreate(savedInstanceState); initSounds();/*初始化声音*/ setContentView(R.layout.main);//设置当前显示的View textView=(TextView)this.findViewById(R.id.textView); button1=(Button)this.findViewById(R.id.button1); button2=(Button)this.findViewById(R.id.button2); button3=(Button)this.findViewById(R.id.button3); button1.setOnClickListener(this); button2.setOnClickListener(this); button3.setOnClickListener(this); } /*初始化声音*/ public void initSounds(){ mMediaPlayer = MediaPlayer.create(this, R.raw.backsound);//初始化MediaPlayer } public void onClick(View v) { if(v == button1){//点击了使用MediaPlayer播放声音按钮 textView.setText("使用MediaPlayer播放声音"); if(!mMediaPlayer.isPlaying()){ mMediaPlayer.start();//播放声音 } } else if(v == button2){//点击了暂停MediaPlayer声音按钮 textView.setText("暂停了MediaPlayer播放的声音"); if(mMediaPlayer.isPlaying()){ mMediaPlayer.pause();//暂停声音 } } else if(v == button3){//停止MediaPlayer播放的声音按钮 textView.setText("停止MediaPlayer播放的声音"); if(mMediaPlayer.isPlaying()){ mMediaPlayer.stop();//停止声音 mMediaPlayer.reset();/*重置播放器*/ initSounds();/*初始化声音*/ } } } }
更多相关文章
- Android状态栏上添加按钮
- Android学习(一) 按钮的事件
- 在Unity中捕捉Android的常用按钮返回事件
- sencha touch中处理Android返回按钮事件
- webrtc native 声音控制
- 给Android的音量按钮添加监听事件
- 多个按钮左右相互挤压效果
- Android Material Design按钮样式设计
- Android 中英文切换(点击按钮切换语言)