Android播放mp3
网页
<?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"
tools:context=".MainActivity">
<Button
android:id="@+id/btnPlay"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="播放"
/>
<Button
android:id="@+id/btnPause"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="暂停"
/>
<Button
android:id="@+id/btnStop"
android:layout_width="100dp"
android:layout_height="50dp"
android:text="停止"
/>
</LinearLayout>
Activity
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import android.Manifest;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.cloudcenter.day05.services.MusicService;
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MusicService.MyBinder myBinder;
private MyConnection mCon;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
init();
}
private void init() {
initView();
// todo activity 与 service绑定启动
Intent intent = new Intent(this, MusicService.class);
//创建链接
mCon = new MyConnection();
//设置连接
bindService(intent, mCon, BIND_AUTO_CREATE);
// startService();
// 权限判断,如果没有权限就请求权限(动态)
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1);
} else {
Toast.makeText(this, "权限已获取!", Toast.LENGTH_SHORT).show();
// initMediaPlayer();//初始化播放器 MediaPlayer
}
}
private void initView() {
Button btnPlay = (Button) findViewById(R.id.btnPlay);
Button btnPause = (Button) findViewById(R.id.btnPause);
Button btnStop = (Button) findViewById(R.id.btnStop);
btnPlay.setOnClickListener(this);
btnPause.setOnClickListener(this);
btnStop.setOnClickListener(this);
}
@Override
public void onClick(View view) {
//根据按钮,设置对应的service方法
switch (view.getId()) {
case R.id.btnPlay:
if (null != myBinder) myBinder.onPlay();
break;
case R.id.btnPause:
if (null != myBinder) myBinder.onPause();
break;
case R.id.btnStop:
if (null != myBinder) myBinder.onStop();
break;
default:
break;
}
}
/**
* todo 连接通道:连接Activity和service
* 创建之后生成这两个方法就行了,不需要其他操作。
*/
private class MyConnection implements ServiceConnection {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
//创建一个全局变量,获取service中的Binder
myBinder = ((MusicService.MyBinder) iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
/**
* app获取权限回掉
*
* @param requestCode
* @param permissions
* @param grantResults
*/
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case 1:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// initMediaPlayer();
} else {
Toast.makeText(this, "拒绝权限,将无法使用程序。", Toast.LENGTH_LONG).show();
finish();
}
break;
default:
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (null != myBinder) myBinder.onDestroy();
//断开service连接
unbindService(mCon);
}
}
Service
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Binder;
import android.os.IBinder;
import java.io.IOException;
/**
* todo Service有两种启动方式:
* onStart:停用了
* onBind:
*/
public class MusicService extends Service {
//媒体播放
private MediaPlayer mMediaPlayer = new MediaPlayer();
private static final String TAG = "MusicService";
private boolean isPrepared = false; // 是否准备完毕
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new MyBinder();
}
@Override
public void onCreate() {
super.onCreate();
//播放
initMusicPlayer();
}
/**
* 播放本地
*/
private void initMusicPlayer() {
try {
//设置播放地址
mMediaPlayer.setDataSource("/sdcard/1.mp3");
//播放。
mMediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 播放线上的媒体文件
*/
private void initNetMusicPlayer() {
try {
//Android9开始,不能直接播放http了,所以若是低于Android的手机,直接这样播放没有问题,但是高版本的Android就不能播放了
mMediaPlayer.setDataSource("http://test-web-back.findmaster.cn:13389/static/good.mp3");
//使用异步播放
mMediaPlayer.prepareAsync();
//添加监听,监听媒体流的加载情况
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
//加载了内容
isPrepared = true;
//直接播放
mMediaPlayer.start();
}
});
} catch (IOException e) {
e.printStackTrace();
}
}
//TODO 创建Binder进行Activity和service的交互
public class MyBinder extends Binder {
/**
* 播放
*/
public void onPlay() {
//若是播放网络资源,需要加载好之后才能播放
// if (!isPrepared) {
// Toast.makeText(MusicService.this, "还未准备好!", Toast.LENGTH_SHORT).show();
// return ;
// }
if (!mMediaPlayer.isPlaying()) {
mMediaPlayer.start();
}
}
public void onPause() {
if (mMediaPlayer.isPlaying()) {
mMediaPlayer.pause();
}
}
public void onStop() {
if (mMediaPlayer.isPlaying()) {
//重新设置
mMediaPlayer.reset();
//播放
initMusicPlayer();
}
}
//销毁
public void onDestroy() {
if (null != mMediaPlayer) {
mMediaPlayer.stop();
mMediaPlayer.release(); // 释放资源
mMediaPlayer = null;
}
}
}
}
权限
<!-- 获取本地的写权限。 -->
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<!-- 获取本地的读权限。 -->
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
播放网络mp3异常
播放的时候,网络不能播放,原因是Android9开始,不能直接播放http了,所以若是低于Android的手机,直接这样播放没有问题,但是高版本的Android就不能播放了.
解决方法:
- 方法1:在
AndroidManifest.xml
的application
标签添加android:usesCleartextTraffic="true"
- 方法2:在访问http之前,调用
setCleartextTrafficPermitted(true)