简单音频扫码提示

进行二维码扫描时,往往需要根据扫描到内容给出相应的音频提示,或正确或不正确。

RawPlayer.java:

/**
 * Created by Sinaan on 2016/12/22.
 * <uses-permission android:name="android.permission.VIBRATE" />
 */
public class RawPlayer {
    private Activity context;
    private MediaPlayer mediaPlayer;
    private Vibrator vibrator;
    private static final float BEEP_VOLUME = 0.10f;
    private static final long VIBRATE_DURATION = 200L;
    public enum Scan{
        CORRECT,ERROR
    }

    public RawPlayer(Activity context) {
        this.context = context;
        if (mediaPlayer == null) {
            vibrator = SystemService.getVibrator(context);
            initBeepSound();
        }
    }

    private void initBeepSound() {
        context.setVolumeControlStream(AudioManager.STREAM_MUSIC);
        mediaPlayer = new MediaPlayer();
        mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
        mediaPlayer.setOnCompletionListener(beepListener);
    }

    public void play(Scan scan) {
        if (mediaPlayer != null) {
            AssetFileDescriptor file ;
            mediaPlayer.reset();
            if(Scan.CORRECT==scan)
                file = context.getResources().openRawResourceFd(R.raw.correct);
            else
                file = context.getResources().openRawResourceFd(R.raw.error);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(), file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
                mediaPlayer.start();

                vibrator.vibrate(VIBRATE_DURATION);
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };
}

调用方法:

MediaPlayer mediaPlayer = new MediaPlayer();
rawPlayer.play(RawPlayer.Scan.CORRECT);、
rawPlayer.play(RawPlayer.Scan.ERROR);
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页