简体   繁体   English

Android声音播放嘈杂且发出嘶哑声

[英]Android sound plays noisy and is crackling

I am having problems with playing sound on android with the SoundPool , this works nicely with the MediaPlayer class. 我在使用SoundPool在android上播放声音时遇到问题,这在MediaPlayer类上很好用。 Why I can't use the MediaPlayer class is because it's not supporting the change of the sound pitch or speed. 我之所以不能使用MediaPlayer类,是因为它不支持音高或速度的改变。

The use case: Sound is played on background and it will be changed based on the user input. 用例:声音在背景上播放,并且将根据用户输入进行更改。

The current problem: Does not play the sound correctly and freezes the application. 当前的问题:无法正确播放声音并冻结了应用程序。

Question: What would be correct way to handle this situation, should the background sound played in separate thread and the communication of changing the sound volume should be done using Handler and messages ? 问题:处理这种情况的正确方法是什么,应该使用Handler和messages完成在单独线程中播放的背景声音以及更改音量的通信吗?

@Override
public void surfaceCreated(SurfaceHolder holder) {

    soundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0);
    RAIN_SOUND_ID =  soundPool.load(getContext(), R.raw.rain, 1);

    new Thread(new Runnable() {
        @Override
        public void run() {


            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {

                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    if (sampleId == RAIN_SOUND_ID) {
                        soundPool.play(RAIN_SOUND_ID, 1f, 1f, 10, -1, 1);
                    }
                }
            });
        }
    }).start();
 }

The SoundPool class actually creates and manages it's own thread pool behind the scenes, for playing it's sounds. SoundPool类实际上是在后台创建和管理自己的线程池,以播放声音。 So you can simplify your code to remove your additional threading as a potential issue. 因此,您可以简化代码以消除其他潜在的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM