安卓播放MP3
多线程
void playOnlineSound(String soundUrlDict) {
try {
Log.i(TAG,"playOnlineSound:"+soundUrlDict);
MediaPlayer mediaPlayer = new MediaPlayer();
if(!TextUtils.isEmpty(soundUrlDict) && !soundUrlDict.contains("/")){//如果不包含"/" 则调用assets内的音频 例xxx.mp3
//获取assets目录下音频文件的AssetFileDescriptor
AssetFileDescriptor afd = getAssets().openFd(soundUrlDict);
//获取AssetFileDescriptor中的 音频文件 / 起始偏移量 / 文件长度:
mediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
}else if(!TextUtils.isEmpty(soundUrlDict) && !soundUrlDict.contains("http")) {
//如果包含"/" 则调用手机文件系统内的音频 例:/storage/emulated/0/KuwoMusic/music/雪.mp3
File file = new File(soundUrlDict);
FileInputStream fis = new FileInputStream(file);
mediaPlayer.setDataSource(fis.getFD());
}else {//调用网络音频 例:http://****/xxx.mp3
mediaPlayer.setDataSource(soundUrlDict);
}
//异步准备播放
mediaPlayer.prepareAsync();
//开始播放
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
@Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
}
});
//释放MediaPlayer对象
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (mp != null) {
mp.release();
}
Log.d(TAG, "onCompletion: play sound.");
}
});
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
@Override
public boolean onError(MediaPlayer mediaPlayer, int i, int i1) {
Log.d(TAG, "Play online sound onError: " + i + ", " + i1);
return false;
}
});
} catch (IOException e1) {
Log.e(TAG, "url: ", e1);
}
}
单线程
void playOnlineSound() {
try {
AssetFileDescriptor assetFileDescriptor = assetManager.openFd("###");//assest下的MP3路径,
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();//获取FileDescriptor
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(fileDescriptor,assetFileDescriptor.getStartOffset(),assetFileDescriptor.getLength());
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e1) {
Log.e(TAG, "url: ", e1);
}
}