聲音合集

系統(tǒng)聲音

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
 * 獲取系統(tǒng)聲音
 */
public class SoundUtils {

    private Ringtone mRingtone;

    public SoundUtils() {
        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        mRingtone = RingtoneManager.getRingtone(getContext(), uri);//通過Uri 來獲取提示音的實(shí)例對(duì)象
        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. 可以使用文件系統(tǒng)

振動(dòng)

Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(500);//震動(dòng)時(shí)長(zhǎng) ms

振動(dòng)需要權(quán)限

<uses-permission name="android.permission.VIBRATE" />

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

友情鏈接更多精彩內(nèi)容