Android-MediaPlayer播放网络音频
官方文档:https://developer.android.google.cn/reference/android/media/MediaPlayer
运行截图:
主布局文件:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="新春乐-纯音乐"
android:textSize="40sp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="50dp">
<Button
android:id="@+id/start"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="开始"
android:textAllCaps="false"
android:textSize="25sp" />
<Button
android:id="@+id/pause"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="暂停"
android:textAllCaps="false"
android:textSize="25sp" />
</LinearLayout>
</LinearLayout>
主类:
/***
* 该Demo是演示MediaPlayer播放网络音频
*/
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button start;
private Button pause;
private MediaPlayer mediaPlayer;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
initMediaPlayer();
}
private void initMediaPlayer() {
try {
mediaPlayer.setDataSource("http://www.ytmp3.cn/down/57799.mp3");
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
private void init() {
start = findViewById(R.id.start);
pause = findViewById(R.id.pause);
start.setOnClickListener(this);
pause.setOnClickListener(this);
mediaPlayer = new MediaPlayer();
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start:
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
break;
case R.id.pause:
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
//音乐地址:http://www.ytmp3.cn/down/57799.mp3
不要忘记在Manifest.xml里添加网络权限:
<uses-permission android:name="android.permission.INTERNET" />