Android: Playing an audio clip onClick

前端 未结 3 872
孤城傲影
孤城傲影 2020-12-08 14:37

How do I set up an audiofile to play when a user touches an image.

Where should I store the audio file and what code should I use to actually play the file? I don\'t

3条回答
  •  独厮守ぢ
    2020-12-08 14:40

    You can also achieve the same using SoundPool.

    MediaPlayer first loads the whole sound data in memory then play, so it produces some lag when we switch among sounds frequently.

    SoundPool is a better option with small size sound file and produces better result with .ogg media file.

    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);
    
     }
    });
    

提交回复
热议问题