SoundPool puse работает только один раз

Это мой код:

    int SC5;
    sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    SC5  = sp.load(this, R.raw.c5, 1);

    C5.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            switch(event.getAction()) {

                case MotionEvent.ACTION_DOWN:
                    // PRESSED
                    sp.play(SC5, 1, 1, 0, 0, 1);
                    return true; 


                case MotionEvent.ACTION_UP:
                    // RELEASED
                    sp.pause(SC5);

                    return true; 
            }
            return false;
        }
    });

Я хочу, чтобы когда я отпустил кнопку, мой звуковой пул перестал воспроизводиться, этот код работает, но только один раз. Когда я нажимаю кнопку во второй раз, я не могу остановить звук и не могу использовать autoPause();, потому что у меня есть другие файлы в этом звуковом пуле.

Пожалуйста помоги


person Danial Barazandeh    schedule 28.09.2016    source источник


Ответы (1)


РЕШЕНИЕ:

int streamId = -1;
C5.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View v, MotionEvent event) {
        switch(event.getAction()) {

            case MotionEvent.ACTION_DOWN:
                // PRESSED
                streamId = sp.play(SC5, 1, 1, 0, 0, 1);
                return true; 


            case MotionEvent.ACTION_UP:
                // RELEASED
                sp.pause(streamId);

                return true; 
        }
        return false;
    }
});

ПОЯСНЕНИЯ

Вы не можете использовать SC5 для приостановки звука, так как SC5 оказывается soundId.

Для получения дополнительной информации вы должны проверить документ SoundPool и ОБРАТИТЬ ВНИМАНИЕ на идентификатор, который вы используете для воспроизведения (soundId) или приостановки (streamId) звука.

 /**
 * Play a sound from a sound ID.
 *
 * Play the sound specified by the soundID. This is the value 
 * returned by the load() function. Returns a non-zero streamID
 * if successful, zero if it fails. The streamID can be used to
 * further control playback. Note that calling play() may cause
 * another sound to stop playing if the maximum number of active
 * streams is exceeded. A loop value of -1 means loop forever,
 * a value of 0 means don't loop, other values indicate the
 * number of repeats, e.g. a value of 1 plays the audio twice.
 * The playback rate allows the application to vary the playback
 * rate (pitch) of the sound. A value of 1.0 means play back at
 * the original frequency. A value of 2.0 means play back twice
 * as fast, and a value of 0.5 means playback at half speed.
 *
 * @param soundID a soundID returned by the load() function
 * @param leftVolume left volume value (range = 0.0 to 1.0)
 * @param rightVolume right volume value (range = 0.0 to 1.0)
 * @param priority stream priority (0 = lowest priority)
 * @param loop loop mode (0 = no loop, -1 = loop forever)
 * @param rate playback rate (1.0 = normal playback, range 0.5 to 2.0)
 * @return non-zero streamID if successful, zero if failed
 */
public final int play(int soundID, float leftVolume, float rightVolume,
        int priority, int loop, float rate);

/**
 * Pause a playback stream.
 *
 * Pause the stream specified by the streamID. This is the
 * value returned by the play() function. If the stream is
 * playing, it will be paused. If the stream is not playing
 * (e.g. is stopped or was previously paused), calling this
 * function will have no effect.
 *
 * @param streamID a streamID returned by the play() function
 */
public final void pause(int streamID); 
person Bennyhuo    schedule 28.09.2016
comment
извините, я редактирую свой пост. теперь вы могли видеть лучше. моя единственная проблема в том, что моя пауза работает только один раз, когда я снова играю, я не могу сделать паузу, но другие вещи работают правильно - person Danial Barazandeh; 28.09.2016
comment
Я знаю, как я уже сказал, вы используете soundId для приостановки звука, это неправильно!! Используйте streamId для паузы, работает нормально. - person Bennyhuo; 28.09.2016
comment
э-э ... Чтобы было понятнее, я обновил свой ответ. Я сделал свою собственную демонстрацию с вашим кодом, и она работала нормально..... - person Bennyhuo; 28.09.2016
comment
спасибо, чувак, я попробовал это снова, и это сработало. спасибо большое ‹3 - person Danial Barazandeh; 28.09.2016