Skip to content

Instantly share code, notes, and snippets.

@tom2cjp
Created September 22, 2012 15:21
Show Gist options
  • Save tom2cjp/3766502 to your computer and use it in GitHub Desktop.
Save tom2cjp/3766502 to your computer and use it in GitHub Desktop.
采用mediaPlayer 管理声音资源
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
public class AudioClip {
private final static String TAG = "AudioClip";
private String name;
private MediaPlayer mPlayer;
protected boolean mLoop;
protected boolean mPlaying;
public AudioClip(Context ctx, int resid) {
name = ctx.getResources().getResourceName(resid);
mPlayer = MediaPlayer.create(ctx, resid);
setInitListener();
}
public AudioClip(Context ctx, Uri uri) {
name = uri.toString();
mPlayer = MediaPlayer.create(ctx, uri);
setInitListener();
}
private void setInitListener() {
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mPlaying = false;
if (mLoop) {
mPlayer.start();
}
}
});
}
public synchronized void play() {
if (mPlaying)
return;
if (mPlayer != null) {
mPlaying = true;
mPlayer.start();
}
}
public synchronized void play(int vol) {
if (mPlayer != null)
mPlayer.setVolume((float) Math.log(vol), (float) Math.log(vol));
play(vol);
}
public synchronized void stop() {
if (!mPlaying)
return;
if (mPlayer != null) {
mLoop = false;
mPlaying = false;
mPlayer.stop();
}
}
public synchronized void loop() {
mLoop = true;
mPlaying = true;
mPlayer.start();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment