Android 安卓-播放和停止声音

Android 安卓-播放和停止声音,android,Android,播放声音并停止它的最佳方式是什么 我尝试使用RingtoneManager、MediaPlayer和SoundPool,但未能停止声音 使用RingtoneManager TYPE_ALARM时,是否有办法停止声音 请给我一个简单的片段 这是我最后一次尝试: SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); List<Integer> streams = new ArrayLis

播放声音并停止它的最佳方式是什么

我尝试使用RingtoneManager、MediaPlayer和SoundPool,但未能停止声音

使用RingtoneManager TYPE_ALARM时,是否有办法停止声音

请给我一个简单的片段

这是我最后一次尝试:

        SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    List<Integer> streams = new ArrayList<Integer>();
    int soundId = pool.load(getApplicationContext(), R.drawable.alarm, 1); //There are several versions of this, pick which fits your sound


    try{

        if(myWifiInfo.getRssi() < -55)
        {
            /*
            Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
            r.play();*/

            Thread.sleep(1000);
            int streamId = -1;
            streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
            streams.add(streamId);
            textRssi.setText(String.valueOf(myWifiInfo.getRssi() + " WARNING"));
        }
        else {
            Log.e("WIFI","Usao");
              for (Integer stream : streams) {
                  pool.stop(stream);
              }
              streams.clear();
            Log.e("WIFI","Izasao");
        }
SoundPool pool=newsoundpool(10,AudioManager.STREAM_MUSIC,0);
列表流=新的ArrayList();
int soundId=pool.load(getApplicationContext(),R.drawable.alarm,1)//这有几个版本,选择适合你的声音
试一试{
if(myWifiInfo.getRssi()<-55)
{
/*
Uri通知=RingtoneManager.getDefaultUri(RingtoneManager.TYPE_通知);
Ringtone r=RingtoneManager.getRingtone(getApplicationContext(),通知);
r、 play()*/
睡眠(1000);
int streamId=-1;
streamId=pool.play(声音id,1.0f,1.0f,1,0,1.0f);
streams.add(streamId);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()+“警告”);
}
否则{
Log.e(“WIFI”、“Usao”);
用于(整数流:流){
池.停(流);
}
流。清除();
Log.e(“WIFI”、“Izasao”);
}

我假设此函数被多次调用?问题是您正在将streamID添加到本地列表中。每次调用函数时都会重新创建该列表,因此当您尝试调用stop时,列表将始终为空


如果它只被调用一次,那么问题是你永远不会调用stop,而只调用play(它们在If的不同分支中).

发布您尝试过的代码。我知道我看到stop方法对MediaPlayer和声音池有效。@Gabeschen编辑了这篇文章。给您。我尝试了您的建议,但无效。声音也会在一定时间后停止播放,但不会在应该的时候停止播放。