在我们的项目中经常会遇到播放声音的功能,在Android中系统的framework已经提供了调用播放声音的API——MediaPlayer
在Android Developers中已经给出了相关的文档:
One of the most important components of the media framework is the MediaPlayer
class. An object of this class can fetch, decode, and play both audio and video with minimal setup. It supports several different media sources such as:
android中的MediaPlayer可以播放多种路径的声音文件 包括 本地资源声音文件,网络声音文件,内部的系统声音
播放本地文件:
使用时首先需要创建Mediaplayer
创建方式一:
MediaPlayer mediaPlayer = MediaPlayer.create(context, R.raw.sound_file_1);
mediaPlayer.start(); // no need to call prepare(); create() does that for you
MediaPlayer player= new MediaPlayer();
//重置播放器
player.reset();
//设置资源文件
player.setDataSource("sdcard/zxmzf.mp3");
//准备就绪
player.prepare();
//播放
player.start();
Uri myUri = ....; // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(getApplicationContext(), myUri);
mediaPlayer.prepare();
mediaPlayer.start();
String url = "http://........"; // your URL here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(url);
mediaPlayer.prepare(); // might take long! (for buffering, etc)
mediaPlayer.start();
mediaPlayer.release();
mediaPlayer = null;
public class MyService extends Service implements MediaPlayer.OnPreparedListener {
private static final String ACTION_PLAY = "com.example.action.PLAY";
MediaPlayer mMediaPlayer = null;
public int onStartCommand(Intent intent, int flags, int startId) {
...
if (intent.getAction().equals(ACTION_PLAY)) {
mMediaPlayer = ... // initialize it here
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.prepareAsync(); // prepare async to not block main thread
}
}
/** Called when MediaPlayer is ready */
public void onPrepared(MediaPlayer player) {
player.start();
}
}