Не останавливается воспроизведение

Программа должна начать цикличное воспроизведение звука при нажатии на кнопку. Звук должен остановиться когда будет нажата другая кнопка. Звук положил в assets

int cancel = -1;
SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
AssetManager assetManager = context.getAssets();
AssetFileDescriptor descriptor;
descriptor = assetManager.openFd("cancel.ogg");
cancel = soundPool.load(descriptor, 0);

На первую кнопку повесил обработчик с методом

soundPool.play(cancel, 1, 1, 0, -1, 1);

На вторую кнопку:

soundPool.stop(cancel);

В результате при нажатии на первую кнопку начинается бесконечное воспроизведение (как и требовалось). Но при нажатии на вторую кнопку воспроизведение не останавливается. Не пойму почему. Где я ошибся?


Ответы (1 шт):

Автор решения: Aziz Umarov

Вы не много путаете идентификаторы потока и ресурса. Нужно взять Stream ID, а не Sound ID. Почитайте подробнее в документации

int streamID = soundPool.play(cancel, 1, 1, 0, -1, 1);

soundPool.stop(streamID);

Правильнее будет делать так

int soundId = -1;
int streamId = -1;

SoundPool soundPool = new SoundPool(10, AudioManager.STREAM_MUSIC,0);
AssetManager assetManager = context.getAssets();
AssetFileDescriptor descriptor;
descriptor = assetManager.openFd("cancel.ogg");
soundId = soundPool.load(descriptor, 0);


// on play
streamId = soundPool.play(soundId, 1, 1, 0, -1, 1);

// on Stop
soundPool.stop(streamId);
→ Ссылка