声音合集

系统声音

package com.ahsoft.tachymeterapp.utils;

import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;

import static org.litepal.LitePalApplication.getContext;

/**
 * created by Taoyuan on 2020/10/23
 * 获取系统声音
 */
public class SoundUtils {

    private Ringtone mRingtone;

    public SoundUtils() {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        mRingtone = RingtoneManager.getRingtone(getContext(), uri);//通过Uri 来获取提示音的实例对象
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
            mRingtone.setLooping(false);
        }
    }

    public void play() {
        if (!mRingtone.isPlaying()) {
            mRingtone.play();
        }
    }

    public void stop() {
        if (mRingtone != null) {
            mRingtone.stop();
            mRingtone = null;
        }
    }

}

资源声音

package com.jty.myutils.utils;

import android.content.Context;
import android.content.res.AssetFileDescriptor;
import android.content.res.AssetManager;
import android.media.MediaPlayer;

import java.io.IOException;

/**
 * created by Taoyuan on 2020/7/3
 */
public class SoundUtils {

    private MediaPlayer player;
    private AssetManager assetManager;

    public SoundUtils(Context context, String fileName) {
        player = new MediaPlayer();
        assetManager = context.getResources().getAssets();
        setDataSource(fileName);
    }

    public void setDataSource(String fileName) {
        try {
            AssetFileDescriptor fileDescriptor = assetManager.openFd(fileName);
            player.setDataSource(
                    fileDescriptor.getFileDescriptor(),
                    fileDescriptor.getStartOffset(),
                    fileDescriptor.getLength());
            player.prepare();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void play() {
        if (!player.isPlaying())
            player.start();
    }

    public void stop() {
        if (player != null && player.isPlaying()) {
            player.stop();
            player.reset();
        }
    }

    public void destroy() {
        if (player != null) {
            player.release();
            player = null;
        }
        if (assetManager != null) {
            assetManager.close();
            assetManager = null;
        }
    }
}

Note

  1. 可以使用raw,可以直接使用 R.raw.资源名称
  2. 以上两种方法均可以直接提供输入流
  3. 可以使用文件系统

振动

Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);//震动时长 ms

振动需要权限

你可能感兴趣的:(声音合集)