SoFunction
Updated on 2025-04-11

How to add sound to keypresses on Android

Adding key sounds to the program's buttons can better affinity with the user and produce a better user experience. The following is how to add sounds to the keys:

public class MainActivity extends Activity {  
  private Button mButton01;  
  private SoundPool sp;//Declare a SoundPool  private int music;//Define an integer and use load(); to set the sundID 
  @Override  
  public void onCreate(Bundle savedInstanceState) {  
 
    (savedInstanceState);  
    setContentView(.activity_main);  
    mButton01=(Button)findViewById(.mButton01);  
    sp= new SoundPool(10, AudioManager.STREAM_SYSTEM, 5);//The first parameter is the maximum number of data streams to play at the same time, the second data stream type, and the third is the sound quality    music = (this, , 1); //Put your sound material into res/raw, the second parameter is the resource file, and the third is the priority of music 
    (new OnClickListener(){  
      @Override  
      public void onClick(View v) {  
       (music, 1, 1, 0, 0, 1);  
    } 
  } 
 } 
} 

During the implementation process, I found that different Android machines have different format requirements for sound resource files.
When the sound resource file format is wma, test on the Android virtual machine, and the keys can make sounds.
Tested on real machine (Meizu M9), logcat displays as follows:

Unable to load sample: (null)
W/SoundPool sample 1 not READY

There is no sound when pressing the button.
Find information and find it in useSoundPoolWhen different machines have different file format requirements.
So the resource file was converted to mp3 format type, but the test found that the situation this time was exactly the opposite, that is, the real machine can play, but the virtual machine cannot.
I thought that in the previous project, the format of the sound resource was ogg, and there was no similar problem. Convert and test decisively, real and virtual machines are fine!

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.