1/* 2 * Copyright (C) 2014 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.camera; 18 19import android.content.Context; 20import android.media.SoundPool; 21import android.util.SparseIntArray; 22 23/** 24 * Loads a plays custom sounds. For playing system-standard sounds for various 25 * camera actions, please refer to {@link SoundClips}. 26 */ 27public class SoundPlayer { 28 private final Context mAppContext; 29 private final SoundPool mSoundPool; 30 /** Keeps a mapping from sound resource ID to sound ID */ 31 private final SparseIntArray mResourceToSoundId = new SparseIntArray(); 32 33 /** 34 * Construct a new sound player. 35 */ 36 public SoundPlayer(Context appContext) { 37 mAppContext = appContext; 38 final int audioType = SoundClips.getAudioTypeForSoundPool(); 39 mSoundPool = new SoundPool(1 /* max streams */, audioType, 0 /* quality */); 40 } 41 42 /** 43 * Load the sound from a resource. 44 */ 45 public void loadSound(int resourceId) { 46 int soundId = mSoundPool.load(mAppContext, resourceId, 1/* priority */); 47 mResourceToSoundId.put(resourceId, soundId); 48 } 49 50 /** 51 * Play the sound with the given resource. The resource has to be loaded 52 * before it can be played, otherwise an exception will be thrown. 53 */ 54 public void play(int resourceId, float volume) { 55 Integer soundId = mResourceToSoundId.get(resourceId); 56 if (soundId == null) { 57 throw new IllegalStateException("Sound not loaded. Must call #loadSound first."); 58 } 59 mSoundPool.play(soundId, volume, volume, 0 /* priority */, 0 /* loop */, 1 /* rate */); 60 } 61 62 /** 63 * Unload the given sound if it's not needed anymore to release memory. 64 */ 65 public void unloadSound(int resourceId) { 66 Integer soundId = mResourceToSoundId.get(resourceId); 67 if (soundId == null) { 68 throw new IllegalStateException("Sound not loaded. Must call #loadSound first."); 69 } 70 mSoundPool.unload(soundId); 71 } 72 73 /** 74 * Call this if you don't need the SoundPlayer anymore. All memory will be 75 * released and the object cannot be re-used. 76 */ 77 public void release() { 78 mSoundPool.release(); 79 } 80} 81