Android:如何播放声音取决于按下的按钮?

时间:2013-09-29 08:20:06

标签: java android audio playback

我是Android新手,我想根据用户按下的按钮播放声音。

我设法按下按钮播放声音,但我必须指定我想要播放的文件。

我想要做的是找到一种动态设置R.raw.arthaswhat5参数的方法,以便将其设置为按下的最后一个按钮。

public void listen(View w){
    MediaPlayer mediaPlayer = MediaPlayer.create(this, R.raw.arthaswhat5);
    mediaPlayer.start();
}

我认为以与我的文件相同的方式命名按钮可能有所帮助,但我真的不明白这个R的工作原理...我知道我可以得到v.getId()int来知道按下了哪个按钮但是我不能用这个id相应地播放声音......

3 个答案:

答案 0 :(得分:1)

您想使用声音池 http://developer.android.com/reference/android/media/SoundPool.html

在“res”文件夹中添加一个名为“raw”的文件夹,并将声音文件放在那里。 我使用.m4a文件,它对我有用,但我不确定支持哪些其他格式。

这是我在我的应用中使用的代码的片段, 播放声音使用以下代码:

int flip = 1,scratch = 2,wrong = 3,correct = 4,pop = 5;
SoundPool soundPool;
HashMap<Integer, Integer> soundPoolMap;

setVolumeControlStream(AudioManager.STREAM_MUSIC);

soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 100);
soundPoolMap = new HashMap<Integer, Integer>();
soundPoolMap.put(flip, soundPool.load(this, R.raw.flip, 1));
soundPoolMap.put(scratch, soundPool.load(this, R.raw.scratch, 1));
soundPoolMap.put(wrong, soundPool.load(this, R.raw.wrong, 1));
soundPoolMap.put(correct, soundPool.load(this, R.raw.correct, 1));
soundPoolMap.put(pop, soundPool.load(this, R.raw.pop, 1));

soundPool.play(soundPoolMap.get(flip), 1, 1, 1, 0, 1);

编辑:几乎完全忽略了你问题的一部分。 您需要使用开关/外壳范围来确定单击哪个按钮并相应地应用正确的声音:

public void listen(View v) {
   switch(v.getId()) {
      case (R.id.button1):
         soundPool.play(soundPoolMap.get(flip), 1, 1, 1, 0, 1);
         break;
      case (R.id.button2):
         soundPool.play(soundPoolMap.get(scratch), 1, 1, 1, 0, 1);
         break;
      case (R.id.button3):
         ...
   }
}

答案 1 :(得分:0)

R.raw类似R.id的基本单词,例如指向这些值存储位置的指针。

在原始文件夹下保存一些图像或wav文件时,在项目刷新后,您可以像R.raw.arthaswhat5一样调用它,返回int

以同样的方式添加新的GUI元素时会生成R.id

R.rawR.id之间没有依赖关系。当R.raw指向您的视图XML时,R.id指向原始文件夹。

from `View` you can fetch id to you it for `if` statement or `switch`

if (v.getId() == R.id.your_button){ /*...*/}  

<强> [编辑]

如果你有&gt;我将使用assets文件夹而不是raw的100首歌曲。因为在raw中,所有名称都必须是小写的,并且您无法创建子目录。将难以处理和维护。

答案 2 :(得分:0)

为什么不使用像这样的switch-case语句?

public void listen(View v){
   MediaPlayer mediaPlayer;
   switch(v.getid()) {
      case (R.id.sound1):
         mediaPlayer = MediaPlayer.create(this, R.raw.arthaswhat5);
         mediaPlayer.start();
         break;
      case (R.id.sound2):
         mediaPlayer = MediaPlayer.create(this, R.raw.arthaswhat6);
         mediaPlayer.start();
         break;
      case (R.id.sound3):
         ...
         ...
         ...
      case (...)
         ...
         ...
         ...
   }
}