android - 在 SoundPool 播放中使用 String

标签 android soundpool

我正在为我的 Android 应用程序使用 SoundPool。我在我的主要 Activity 中将大约 75 个一到三秒的声音加载到池中,然后使用 Sound 方法从其他 Activity 中引用它们,如下所示:

    public void Sound(int s){
    AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
    float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
    MainActivity.spool.play(s, volume, volume, 1, 0, 1f);
};

s是我在MainActivity类中定义的整数,例如:

static int sound_e;

然后像这样传入 Sound 方法:

Sound(sound_e);

我希望能够像这样定义一个字符串:

String letter_sound = "MainActivity.sound_" + currentLetter; 
//Example value of this string would be MainActivity.sound_a

然后将该字符串作为整数传递给 Sound。这是为了避免 26 个 if 语句,我是这样处理数字的:

if (randomNum == 1) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_1);}
        else if (randomNum == 2) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_2);}
        else if (randomNum == 3) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_3);}
        else if (randomNum == 4) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_4);}
        else if (randomNum == 5) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_5);}
        else if (randomNum == 6) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_6);}
        else if (randomNum == 7) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_7);}
        else if (randomNum == 8) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_8);}
        else if (randomNum == 9) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_9);}
        else if (randomNum == 10) {Log.v(TAG,  "Sound playing for: " + randomNum); Sound(MainActivity.sound_10);}
        else Log.v(TAG, "None of the ifs are true. randomNum: " + randomNum);

我没有在 android 文档中看到任何将字符串值传递到 SoundPool play 的方法,只有整数。感谢您帮助我弄清楚我遗漏了什么!

最佳答案

I'm using SoundPool for my android app. I load about 75 one- to three-second sounds into the pool in my main activity and then reference them from other activities using the Sound method...

首先……不要这样做。 Android Activity 类不仅仅是一个普通的 Java 类,正确(且安全)的 Android 编程方法是 Activity 应该是自包含的。其他 Activity 或应用程序组件不应访问 public 方法或数据字段。

如果您不想提供一个供多个应用程序组件使用的公共(public)类,那么只需创建一个“助手”POJO 类即可。如果它需要使用 Context(例如 SoundPool),您可以简单地将 Activity 上下文作为 this 传递到方法中。持有对 Activity Context 的引用时要小心,因为它可能会导致内存泄漏。

其次给你的问题一个简单的答案...

SoundPoolload(...) 方法返回一个 soundID,这是您用来调用 play( ...) 方法。如果您只想播放随机声音,则只需创建某种数组并使用随机数按索引从数组中获取 soundID。简单 - 只需一行代码即可访问相关的 soundID

关于android - 在 SoundPool 播放中使用 String,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18346219/

相关文章:

安卓异步任务问题

android - MediaPlayer无法播放服务器中的某些音频文件

android - Sound Pool 只播放一次声音

Android .ogg 文件在几秒钟后停止播放

安卓音频 : change pitch

android - 如何在用户执行任何操作时关闭 Snackbar?

android - rxandroid lambda 与改造

Android:如何确定 IntentService 是否正在运行?

android - Android:播放心率BPM声音

java - 如何使音池静音?