日照市东港区创新电子技术中心
ndfweb.cn

Android 发出自定义(频率,持续时间)的声音


2021-07-02 11:12:45 (3360)


在stackoverflow看到两个库,挺有用的
传送门1 1.https://github.com/m-abboud/android-tone-player 下面是使用方式

OneTimeBuzzer buzzer = new OneTimeBuzzer();buzzer.setDuration(5);// volume values are from 0-100buzzer.setVolume(50);buzzer.setToneFreqInHz(110);

传送门2 https://github.com/karlotoy/perfectTune  使用方式github上有

然后最后一种是自己写的

public class AudioTrackManager {
    private Thread mRecordThread;
    AudioTrack mAudioTrack;
    private volatile static AudioTrackManager mInstance;

    public static AudioTrackManager getInstance() {
        if (mInstance == null) {
            synchronized (AudioTrackManager.class) {
                if (mInstance == null) {
                    mInstance = new AudioTrackManager();
                }
            }
        }
        return mInstance;
    }


    /**
     * Play beep.
     * @param duration     the duration
     * @param frequency_hz the frequency hz
     */
    public void playBeep(int duration,int frequency_hz) {
        destroyThread();
        // int duration = 5; // duration of sound
        // double freqOfTone = 440; // hz

        final int sampleRate = 8000;
        final int numSamples = duration * sampleRate;
        final double samples[] = new double[numSamples];
        final short buffer[] = new short[numSamples];
        for (int i = 0; i < numSamples; ++i) {
            samples[i] = Math.sin(2 * Math.PI * i / (sampleRate / frequency_hz));
            buffer[i] = (short) (samples[i] * Short.MAX_VALUE);
        }
         mAudioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRate, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, buffer.length, AudioTrack.MODE_STATIC);

        Runnable recordRunnable = new Runnable() {
            @Override
            public void run() {
                mAudioTrack.write(buffer, 0, buffer.length);
                mAudioTrack.play();
            }
        };
        mRecordThread= new Thread(recordRunnable);
        mRecordThread.start();
    }
    private void destroyThread() {
        try {
            mAudioTrack.stop();
            mRecordThread.interrupt();
            mAudioTrack=null;
            mRecordThread = null;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            mRecordThread = null;
            mAudioTrack=null;
        }
    }}




了解更多请访问:http://www.ndfweb.cn/news-873.html
  NDF俱乐部
  国际域名注册
  建站咨询
合作伙伴:万网 | 新网 | 新网互联 NDF网站建设淘宝店 | 实用工具 | 外貿網站建設 | 联系我们
鲁公网安备 37110202000336号 Sitemap - RSSRSS订阅