MediaPlayer播放

丁鸿云
2023-12-01

在官方4.4的API中说明是这样:

MediaPlayer class can be used to control playback of audio/video files and streams. An example on how to use the methods in this class can be found in VideoView. 
那么可以知道MediaPlayer用于播放音频和视频的接口;


一般情况下,播放音乐都会使用到MediaPlayer;

public static void play(String path) {
	if(mediaPlayer!=null){
		try {
			mediaPlayer.reset();
			mediaPlayer.setLooping(true);
 			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
 			mediaPlayer.setDataSource(path);
 			mediaPlayer.prepare();
  			mediaPlayer.start();
			
		} catch (IllegalStateException e) {
			// Exception
		} catch (IllegalArgumentException e) {
			// Exception
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}


这里需要用到MediaPlayer的相关接口,所以需要实例化一个MediaPlayer对象;
mediaPlayer = new MediaPlayer();


上面用到的
mediaPlayer.reset();
mediaPlayer.setLooping(true);


其实也是可以不用的,不过reset() 最好是能够使用,因为避免上一次播放的时候资源还在占用中导致再次播放出现异常;

路径是sd卡根目录下:
public static String path = Environment.getExternalStorageDirectory() + File.separator+
"music_test.wav";


至此,播放音乐已经完成;
可以注意一下以下接口:

boolean  isLooping() 

Checks whether the MediaPlayer is looping or non-looping. 

boolean  isPlaying() 
Checks whether the MediaPlayer is playing. 

void  pause() 
Pauses playback. 

void  prepare() 
Prepares the player for playback, synchronously. 

void  prepareAsync() 
Prepares the player for playback, asynchronously. 

void  release() 
Releases resources associated with this MediaPlayer object. 

void  reset() 
Resets the MediaPlayer to its uninitialized state. 

void start() 
Starts or resumes playback. 

void  stop() 
Stops playback after playback has been stopped or paused. 





 类似资料: