Как и в заголовках, когда я устанавливаю переключатель через пользовательский интерфейс для воспроизведения my_sound1, сначала все работает, как и ожидалось, но если сначала нажать переключатель для my_sound2, это похоже на то, что buttonId поменяется местами.
Я много раз повторял это и, похоже, не могу найти другой случай, когда у кого-то есть такая же проблема. Сначала я думал, что это ошибка в Soundpool, но теперь я уверен, что это в коде OnCheckedChangeListener.
Если я сначала играю в «Сверчки», приложение работает так, как я хочу. Но если я сначала играю в «Лягушек», это приводит к тому, что программа работает так, как будто меняются идентификаторы переключателей. Я протестировал его в Android 4.1.2, 5.1.1, 7.1.1, и это происходит во всех трех.
Не правильно ли я настроил переключатели? Это ошибка в Android?
MainActivity.java:
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.media.SoundPool.OnLoadCompleteListener;
import android.media.SoundPool;
import android.media.AudioManager;
import android.widget.CompoundButton;
import android.widget.Switch;
public class MainActivity extends AppCompatActivity {
private SoundPool soundPool;
private int my_sound1;
private int my_sound2;
boolean plays1 = false, plays2 = false, loaded_crickets = false, loaded_frogs = false;
float actVolume, maxVolume, volume;
AudioManager audioManager;
private Switch crickets_switch;
private Switch frogs_switch;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// AudioManager audio settings for adjusting the volume
audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
actVolume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
maxVolume = (float) audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
volume = actVolume / maxVolume;
//Hardware buttons setting to adjust the media sound
this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
soundPool = (new SoundPool.Builder()).setMaxStreams(2).build();
}else{
soundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
}
my_sound1 = soundPool.load(this, R.raw.crickets, 1);
my_sound2 = soundPool.load(this, R.raw.frogs, 2);
soundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
public void onLoadComplete(SoundPool soundPool, int sampleId,int status) {
if (sampleId == my_sound1) { loaded_crickets = true; }
if (sampleId == my_sound2) { loaded_frogs = true; }
}
});
crickets_switch = findViewById(R.id.switch1);
frogs_switch = findViewById(R.id.switch2);
crickets_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton crickets_switch, boolean isCheckedCrickets) {
if (isCheckedCrickets) {
if (loaded_crickets && !plays1) {
soundPool.play(my_sound1, volume, volume, 1, -1, 1f);
plays1 = true;
} else {
soundPool.resume(my_sound1);
}
}
if (!isCheckedCrickets && plays1 == true) {
soundPool.pause(my_sound1);
}
}
});
frogs_switch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton frogs_switch, boolean isCheckedFrogs) {
if (isCheckedFrogs) {
if (loaded_frogs && !plays2) {
soundPool.play(my_sound2, volume, volume, 2, -1, 1f);
plays2 = true;
} else {
soundPool.resume(my_sound2);
}
}
if (!isCheckedFrogs && plays2 == true) {
soundPool.pause(my_sound2);
}
}
});
}
}
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Switch
android:id="@+id/switch1"
android:layout_width="173dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="@string/crickets"
app:layout_constraintBottom_toTopOf="@+id/switch2"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Switch
android:id="@+id/switch2"
android:layout_width="176dp"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginLeft="8dp"
android:layout_marginTop="8dp"
android:layout_marginEnd="8dp"
android:layout_marginRight="8dp"
android:layout_marginBottom="8dp"
android:text="@string/frogs"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.506"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent" />
</android.support.constraint.ConstraintLayout>