使用网址或本地的音乐
进行播放,暂停,继续,停止
MainActivity
public class MainActivity extends AppCompatActivity {
private Button btn_start;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
btn_start=findViewById(R.id.btn_start);
mediaPlayer= new MediaPlayer();
btn_start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//可以是本地,也可以是网址
try {
//TODO 以是本地,也可以是网址
mediaPlayer.setDataSource("https://webfs.yun.kugou.com/202003061606/7e5aba9650927d6d4398db8281334289/G001/M00/12/00/QQ0DAFSOlqOAWSenAEeoFiTyFYo800.mp3");
//用异步的方式运行
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
});
}
//暂停
public void pause(View view) {
mediaPlayer.pause();
}
//继续
public void start(View view) {
mediaPlayer.start();
}
//结束
public void stop(View view) {
mediaPlayer.stop();
}
}
MainActivity
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/btn_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="播放音乐"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="pause"
android:text="暂停"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="start"
android:text="回复播放"
/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="stop"
android:text="停止"
/>
</LinearLayout>
来源:CSDN
作者:淮北与枳
链接:https://blog.csdn.net/u011326215/article/details/104758746