您的位置:首页 > 移动开发 > Android开发

Android新手入手教程 -1.使用MediaPlayer播放声音

2017-10-18 14:42 633 查看
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 mediaplayer