FastFoodCoding

Login


Connect with one of the following accounts





Login

Please wait while we redirect...

Views: 213   



Following program shows you how to create your own sound pool and play sounds by passing id.

package com.test;

import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Build;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Random;

public class SoundUtils {
    static SoundPool soundPool;
    static HashMap<Integer, Integer> soundPoolMap;
    static boolean muted = false;

    public static void loadSounds(Context context){
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                AudioAttributes audioAttrib = new AudioAttributes.Builder()
                        .setUsage(AudioAttributes.USAGE_GAME)
                        .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                        .build();
                soundPool = new SoundPool.Builder().setAudioAttributes(audioAttrib).setMaxStreams(6).build();
            }
            else {
                soundPool = new SoundPool(6, AudioManager.STREAM_MUSIC, 0);
            }
            soundPoolMap = new HashMap<Integer, Integer>();
            soundPoolMap.put(1, soundPool.load(context, R.raw.sound_input, 1));
            soundPoolMap.put(2, soundPool.load(context, R.raw.sound_erase, 1));
            soundPoolMap.put(3, soundPool.load(context, R.raw.sound_correct, 1));
            soundPoolMap.put(4, soundPool.load(context, R.raw.sound_wrong, 1));
        }catch (Exception e){
            // Ignore
        }
    }

    public static void playSound(int i){
        try {
            if(!muted && soundPoolMap.containsKey(i)){
                soundPool.play(soundPoolMap.get(i), 1, 1, 1, 0, 1f);
            }
        }catch (Exception e){
            // Ignore
        }
    }
}



On By


Top Tutorials

Top Questions

Top Articles

Top Blogs

Top News