I am working on a project in which I have to load 6 different sounds in one action and play all the sound at the click of a button. The sound file is not so big, but the problem is that maybe they will be more. So my question is what is the fastest way to load sound files into one asset. For testing purposes, I used a res / raw folder for storing audio files and tried using two different ways to play the files, but the result did not satisfy me. Here are two different types of code:
Method 1:
Button first = (Button) findViewById(R.id.one); Button second = (Button) findViewById(R.id.two); first.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { MediaPlayer mp = MediaPlayer.create(SoundFXActivity.this, R.raw.drumtwo); mp.start(); mp.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) {
Method 2:
private SoundPool spool; private int soundID,soundID2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); this.setVolumeControlStream(AudioManager.STREAM_MUSIC); spool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0); soundID = spool.load(this, R.raw.drumone, 1); soundID2 = spool.load(this, R.raw.drumtwo, 1); Button three = (Button) findViewById(R.id.three); three.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Sound(); } }); } public void Sound(){ AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE); float volume = (float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC); spool.play(soundID, volume, volume, 1, 0, 1f); };
But the problem is that both methods are slow. I need to find a way for a faster way to play sounds ... but now, like after almost a second, I press a button to play the sound.
Can you give me some tips on how to play sounda faster. Should I load them into the cache when the application starts or saves them in a database or somewhere else (I don't think the database is a good option as a fact, but I want to hear some suggestions). Maybe download them from the resources folder, but I think it will still be slow.
So any ideas or suggestions? Thanks in advance!
source share