Android:在onClick上播放音频片段

时间:2010-06-15 00:04:49

标签: android audio

如何设置在用户触摸图像时播放的音频文件。

我应该在哪里存储音频文件以及我应该使用哪些代码来实际播放文件? 我不想提出MediaPlayer界面或类似的东西。

我想这样做:

foo = (ImageView)this.findViewById(R.id.foo);
    foo.setOnClickListener(this);

public void onClick(View v) {
if (foo.isTouched()) {

 playAudioFile();
  }
}

由于

3 个答案:

答案 0 :(得分:59)

这不会创建一个MediaPlayer界面......它只会播放你想要的声音。

Button boton = (Button) findViewById(R.id.boton);
boton.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {
  MediaPlayer mp = MediaPlayer.create(TestSonido.this, R.raw.slayer);  
  mp.start();
 }
});

在这种情况下,R.raw.slayer代表一个名为slayer.mp3的音频文件,该文件存储在res/raw/文件夹中,一旦您点击按钮,机器人就会摇滚你...

答案 1 :(得分:1)

您也可以使用SoundPool来达到相同的目的。

MediaPlayer首先将整个声音数据加载到内存中,然后播放,因此当我们频繁切换声音时会产生一些滞后。

SoundPool是声音文件较小的更好选择,对于.ogg媒体文件,效果更好。

SoundPool pl = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
        // 5 indicates the maximum number of simultaneous streams for this SoundPool object
pl.setOnLoadCompleteListener(new OnLoadCompleteListener() {             
            @Override
            public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                // The onLoadComplet method is called when a sound has completed loading.
                soundPool.play(sampleId, 1f, 1f, 0, 0, 1);
                // second and third parameters indicates left and right value (range = 0.0 to 1.0)
            }
});

Button btn = findViewById(R.id.boton);
btn.setOnClickListener(new View.OnClickListener() {
 @Override
 public void onClick(View v) {

     int sound = pl.load(this, R.raw.sound_01, 0);

 }
});

答案 2 :(得分:0)

public void aud_play(View view) {
  if (mp.isPlaying()) {   

   //this if condition doesn't allow the audio file to be played 
         multiple times on multiple clicks of **Play button**

  } 
  else {
    //else the **Play button** plays the audio file

    mp = MediaPlayer.create(this, R.raw.audio_name);
    mp.start();   
  }
}
相关问题