类android.media.SoundPool源码实例Demo

下面列出了怎么用android.media.SoundPool的API类实例代码及写法,或者点击链接到github查看源代码。

源代码1 项目: 2DScroller   文件: TwoDScrollerListview.java
/**
 * To play sound.
 * 
 * @param context
 * 					{@link Context}
 * 
 * @param soundID
 * 					sound id.
 * 	
 * @param soundPool
 * 					{@link SoundPool} instance.
 * 
 */
public void playSound(Context context, int soundID, SoundPool soundPool){
	OnAudioFocusChangeListener afChangeListener = new OnAudioFocusChangeListener() {
		public void onAudioFocusChange(int focusChange) {
			if (focusChange == AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
				// Lower the volume
			} else if (focusChange == AudioManager.AUDIOFOCUS_GAIN) {
				// Raise it back to normal
			}
		}
	};
	AudioManager audioManager = (AudioManager)context.getSystemService(Context.AUDIO_SERVICE);

	// Request audio focus for playback
	int result = audioManager.requestAudioFocus(afChangeListener,
			// Use the music stream.
			AudioManager.STREAM_MUSIC,
			// Request permanent focus.
			AudioManager.AUDIOFOCUS_GAIN);

	if (result == AudioManager.AUDIOFOCUS_REQUEST_GRANTED) {
		// Start playback.
		soundPool.play(soundID, 10, 10, 1, 0,1f );
	}
}
 
源代码2 项目: gdk-timer-sample   文件: TimerView.java
public TimerView(Context context, AttributeSet attrs, int style) {
    super(context, attrs, style);

    mSoundPool = new SoundPool(MAX_STREAMS, AudioManager.STREAM_MUSIC, 0);
    mTimerFinishedSoundId = mSoundPool.load(context, R.raw.timer_finished, SOUND_PRIORITY);

    LayoutInflater.from(context).inflate(R.layout.card_timer, this);

    mHoursView = (TextView) findViewById(R.id.hours);
    mMinutesView = (TextView) findViewById(R.id.minutes);
    mSecondsView = (TextView) findViewById(R.id.seconds);
    mTipView = (TextView) findViewById(R.id.tip);
    mTipView.setText(context.getResources().getString(R.string.timer_finished));
    mTipView.setVisibility(View.INVISIBLE);

    mWhiteColor = context.getResources().getColor(R.color.white);
    mRedColor = context.getResources().getColor(R.color.red);
}
 
源代码3 项目: AndroidWallet   文件: CaptureActivity.java
/**
 * 初始化音效
 */
private void initSound() {
    mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    AssetFileDescriptor descriptor = null;
    try {
        descriptor = getResources().openRawResourceFd(R.raw.beep);
        mSoundId = mSoundPool.load(descriptor, 1);
    } finally {
        if (descriptor != null) {
            try {
                descriptor.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
 
源代码4 项目: MikuMikuStudio   文件: AndroidAudioRenderer.java
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
    AudioNode src = mapLoadingAudioNodes.get(sampleId);
    if (src.getAudioData() instanceof AndroidAudioData) {
        AndroidAudioData audioData = (AndroidAudioData) src.getAudioData();

        if (status == 0) // load was successfull
        {
            int channelIndex;
            channelIndex = soundPool.play(audioData.getId(), 1f, 1f, 1, -1, 1f);
            src.setChannel(channelIndex);
            // Playing started ?
            if (src.getChannel() > 0) {
                src.setStatus(Status.Playing);
            }
        } else {
            src.setChannel(-1);
        }
    } else {
        throw new IllegalArgumentException("AudioData is not of type AndroidAudioData for AudioNode " + src.toString());
    }
}
 
源代码5 项目: Earlybird   文件: Cocos2dxSound.java
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
	if (status == 0)
	{
		// only play effect that are in mEffecToPlayWhenLoadedArray
		for ( SoundInfoForLoadedCompleted info : mEffecToPlayWhenLoadedArray) {
			if (sampleId == info.soundID) {
				// set the stream id which will be returned by playEffect()
				mStreamIdSyn = doPlayEffect(info.path, info.soundID, info.isLoop, info.pitch, info.pan, info.gain);

				// remove it from array, because we will break here
				// so it is safe to do
				mEffecToPlayWhenLoadedArray.remove(info);

				break;
			}
		}
	} else {
		mStreamIdSyn = Cocos2dxSound.INVALID_SOUND_ID;
	}

	mSemaphore.release();
}
 
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final Button button1 = findViewById(R.id.button1);
    button1.setEnabled(false);
    final Button button2 = findViewById(R.id.button2);
    button2.setEnabled(false);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        createSoundPoolNew();
    } else {
        createSoundPoolOld();
    }
    mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            button1.setEnabled(true);
            button2.setEnabled(true);
        }
    });
    mHashMap = new HashMap<>();
    mHashMap.put(1, mSoundPool.load(this, R.raw.sound_1, 1));
    mHashMap.put(2, mSoundPool.load(this, R.raw.sound_2, 1));
}
 
源代码7 项目: homescreenarcade   文件: SoundEngine.java
public SoundEngine(Context context) {
		this.context = context;

		sounds = new SoundPool(5, AudioManager.STREAM_RING, 0);

		soundsMap = new HashMap<Integer, Integer>();
		soundsMap.put(EATFOOD, sounds.load(context, R.raw.pacmon_waka_waka, 1));
		soundsMap.put(EATGHOST, sounds.load(context, R.raw.pacmon_eating_ghost, 1));
		soundsMap.put(DIE, sounds.load(context, R.raw.pacmon_dies, 1));
		soundsMap.put(READY, sounds.load(context, R.raw.pacmon_opening_song,1));
		soundsMap.put(GAMEOVER, sounds.load(context, R.raw.pacmon_opening_song, 1));
		//soundsMap.put(EATCHERRY, sounds.load(context, R.raw.pacmon_eating_cherry, 1));
		
		AudioManager mgr = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
		
	    // the music that is played at the beginning
//	    music = MediaPlayer.create(context, R.raw.gameplaymusic);
//	    music.setLooping(true);
	}
 
源代码8 项目: Ticket-Analysis   文件: CodeGenerateActivity.java
private void shake() {
    SoundPool soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
    int weiChatAudio = soundPool.load(CodeGenerateActivity.this, R.raw.weichat_audio, 1);
    Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
    //发出提示音
    soundPool.play(weiChatAudio, 1, 1, 0, 0, 1);
    vibrator.vibrate(300);
    generateGroup();
    isShaking = true;
    try {
        Thread.sleep(100);
        isShaking = false;
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}
 
源代码9 项目: United4   文件: United.java
/**
 * Makes a new sound pool, loads the requested sound and plays it once it's loaded
 * Could be made a LOT better by reusing the same pool and checking if it's already loaded
 *
 * @param file the sound to play
 */
public static void playSound(String file) {
    if (P.getBool("mute_sounds")) return;
    SoundPool pool = buildPool();
    try {
        AssetFileDescriptor fd = getContext().getAssets().openFd(file);
        pool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
            @Override
            public void onLoadComplete(SoundPool soundPool, int i, int i1) {
                soundPool.play(i, 1, 1, 1, 0, 1);
            }
        });
        pool.load(fd, 1);
    } catch (Exception ignored) {
        //
    }
}
 
源代码10 项目: ssj   文件: AudioAction.java
public void registerWithPlayer(SoundPool player)
{
    try
    {
        if(fd != null)
        {
            soundId = player.load(fd, 1);
            fd.close();
        }
        else
        {
            soundId = player.load(res, 1);
        }
    }
    catch (IOException e)
    {
        Log.e("error loading audio files", e);
    }
}
 
源代码11 项目: brailleback   文件: FeedbackController.java
/**
 * Constructs and initializes a new feedback controller.
 */
public FeedbackController(Context context) {
    mContext = context;
    mResources = context.getResources();
    mVibrator = (Vibrator) mContext.getSystemService(Context.VIBRATOR_SERVICE);
    mSoundPool = new SoundPool(NUMBER_OF_CHANNELS, DEFAULT_STREAM, 1);
    mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            if (status == 0) {
                synchronized (mPostLoadPlayables) {
                    if (mPostLoadPlayables.contains(sampleId)) {
                        soundPool.play(
                                sampleId, DEFAULT_VOLUME, DEFAULT_VOLUME, 1, 0, DEFAULT_RATE);
                        mPostLoadPlayables.remove(Integer.valueOf(sampleId));
                    }
                }
            }
        }
    });
    mHandler = new Handler();

    mResourceIdToSoundMap.clear();
    mResourceIdToVibrationPatternMap.clear();
    MidiUtils.purgeMidiTempFiles(context);
}
 
源代码12 项目: vocefiscal-android   文件: CameraActivity.java
private void setupSound() 
{		
	spool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
	spool.setOnLoadCompleteListener(new OnLoadCompleteListener() 
	{

		@Override
		public void onLoadComplete(SoundPool soundPool, int sampleId, int status) 
		{
			if(status==0)
			{
				if(sampleId==soundID)
					canPlaySound = true;
			}				
		}
	});


	soundID = spool.load(getApplicationContext(), R.raw.one_click, 1);
}
 
源代码13 项目: Example-of-Cocos2DX   文件: Cocos2dxSound.java
@Override
public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
	if (status == 0)
	{
		// only play effect that are in mEffecToPlayWhenLoadedArray
		for ( SoundInfoForLoadedCompleted info : mEffecToPlayWhenLoadedArray) {
			if (sampleId == info.soundID) {
				// set the stream id which will be returned by playEffect()
				mStreamIdSyn = doPlayEffect(info.path, info.soundID, info.isLoop, info.pitch, info.pan, info.gain);

				// remove it from array, because we will break here
				// so it is safe to do
				mEffecToPlayWhenLoadedArray.remove(info);

				break;
			}
		}
	} else {
		mStreamIdSyn = Cocos2dxSound.INVALID_SOUND_ID;
	}

	mSemaphore.release();
}
 
源代码14 项目: mollyim-android   文件: AudioManagerCompat.java
@Override
public SoundPool createSoundPool() {
  return new SoundPool.Builder()
                      .setAudioAttributes(AUDIO_ATTRIBUTES)
                      .setMaxStreams(1)
                      .build();
}
 
源代码15 项目: mollyim-android   文件: AudioManagerCompat.java
@Override
public SoundPool createSoundPool() {
  return new SoundPool.Builder()
                      .setAudioAttributes(AUDIO_ATTRIBUTES)
                      .setMaxStreams(1)
                      .build();
}
 
源代码16 项目: fanfouapp-opensource   文件: SoundManager.java
/**
 * Initialises the storage for the sounds
 * 
 * @param theContext
 *            The Application context
 */
public static void initSounds(final Activity context) {
    SoundManager.mContext = context;
    SoundManager.mAudioManager = (AudioManager) SoundManager.mContext
            .getSystemService(Context.AUDIO_SERVICE);
    SoundManager.mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
}
 
源代码17 项目: Word-Search-Game   文件: SoundPlayer.java
private void init(Context context) {
    mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    mSoundPoolMap = new SparseIntArray();

    mSoundPoolMap.put(Sound.Correct.ordinal(),
            mSoundPool.load(context, R.raw.correct, 1));
    mSoundPoolMap.put(Sound.Wrong.ordinal(),
            mSoundPool.load(context, R.raw.wrong, 1));
}
 
源代码18 项目: homescreenarcade   文件: VPSoundpool.java
public static void initSounds(Context theContext) {
    Log.v(LOG_TAG, "initSounds");
    mContext = theContext;
    mSoundPool = new SoundPool(32, AudioManager.STREAM_RING, 0);
    mSoundPoolMap = new HashMap<Integer, Integer>();
    mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}
 
源代码19 项目: appcan-android   文件: GSenseView.java
private void init() {
    finder = ResoureFinder.getInstance(getContext());
    soundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    soundId = soundPool.load(getContext(), finder.getRawId("collision"), 1);
    touchSlop = ViewConfiguration.get(getContext()).getScaledTouchSlop();
    DisplayMetrics dm = getResources().getDisplayMetrics();
    bitmapBall = BitmapFactory.decodeResource(getResources(), finder.getDrawableId("platform_myspace_ball"));
    bitmapHole = BitmapFactory.decodeResource(getResources(), finder.getDrawableId("platform_myspace_hole"));
    bitmapW = bitmapBall.getWidth();
    bitmapH = bitmapBall.getHeight();
    radius = bitmapW / 2;
    dissAreaLeft = 200 * dm.density;
    dissAreaTop = 50 * dm.density;
    dissAreaRight = dissAreaLeft + bitmapHole.getWidth();
    dissAreaBottom = dissAreaTop + bitmapHole.getHeight();
    activity = (Activity) getContext();
    Rect rectgle = new Rect();
    Window window = activity.getWindow();
    window.getDecorView().getWindowVisibleDisplayFrame(rectgle);
    windowWidth = rectgle.width();
    windowHeight = rectgle.height();
    mVibrator = (Vibrator) activity.getApplication().getSystemService(Service.VIBRATOR_SERVICE);
    sm = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
    setBackgroundDrawable(finder.getDrawable("platform_myspace_gsense_bg_shape"));
    params = new WindowManager.LayoutParams();
    params.height = windowHeight;
    params.width = windowWidth;
    params.type = WindowManager.LayoutParams.TYPE_APPLICATION | WindowManager.LayoutParams.FIRST_SUB_WINDOW;
    params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
            | WindowManager.LayoutParams.FLAG_BLUR_BEHIND;// 模态,不能获得焦点,背景失焦
    params.alpha = 1.0f;
    params.format = PixelFormat.TRANSPARENT;
    params.gravity = Gravity.LEFT | Gravity.TOP;
    params.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
    params.x = dm.widthPixels - windowWidth;
    params.y = dm.heightPixels - windowHeight;
    params.windowAnimations = finder.getStyleId("Anim_platform_myspace_fade");
}
 
源代码20 项目: RecyclerWheelPicker   文件: RecyclerWheelPicker.java
private void initSound() {
    mSoundPool = new SoundPool(50, AudioManager.STREAM_SYSTEM, 5);
    try {
        mSoundPool.load(getContext(), R.raw.wheelpickerkeypress, 1);
    } catch (Exception e) {
    }
}
 
源代码21 项目: gdk-charades-sample   文件: GameResultsActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
    CharadesModel model = (CharadesModel) getIntent().getSerializableExtra(EXTRA_MODEL);

    mCardMargin = (int) getResources().getDimension(R.dimen.card_margin);

    mCardScroller = new CardScrollView(this);
    mCardScroller.setHorizontalScrollBarEnabled(true);
    mCardScroller.setAdapter(
            new CharadesResultsAdapter(getLayoutInflater(), getResources(), model));
    mCardScroller.setOnItemClickListener(mOnClickListener);
    mCardScroller.activate();
    setContentView(mCardScroller);

    // Initialize the sound pool and play the losing or winning sound immediately once it has
    // been loaded.
    mSoundPool = new SoundPool(1, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(sampleId, 1.0f, 1.0f, 0, 0, 1.0f);
        }
    });
    int soundResId = model.areAllPhrasesGuessedCorrectly() ?
            R.raw.triumph : R.raw.sad_trombone;
    mSoundPool.load(this, soundResId, 0);
}
 
源代码22 项目: Huochexing12306   文件: BgdService2.java
private void doAlarm() {
	if (mCurrMInfo.isVibrate()){
		mVibrator.vibrate(1000);
	}
	if (mCurrMInfo.isRing()){
		SoundPool soundPool = new SoundPool(2, AudioManager.STREAM_SYSTEM, 5);
		soundPool.load(this, R.raw.ticket_alarm, 1);
		soundPool.play(1, 1, 1, 0, 0, 1);
	}
}
 
源代码23 项目: AndroidProgramming3e   文件: BeatBox.java
public BeatBox(Context context) {
    mAssets = context.getAssets();
    // This old constructor is deprecated, but we need it for
    // compatibility.
    //noinspection deprecation
    mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
    loadSounds();
}
 
源代码24 项目: AndroidProgramming3e   文件: BeatBox.java
public BeatBox(Context context) {
    mAssets = context.getAssets();
    // This old constructor is deprecated, but we need it for
    // compatibility.
    //noinspection deprecation
    mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
    loadSounds();
}
 
源代码25 项目: AndroidProgramming3e   文件: BeatBox.java
public BeatBox(Context context) {
    mAssets = context.getAssets();
    // This old constructor is deprecated, but we need it for
    // compatibility.
    //noinspection deprecation
    mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
    loadSounds();
}
 
源代码26 项目: AndroidProgramming3e   文件: BeatBox.java
public BeatBox(Context context) {
    mAssets = context.getAssets();
    // This old constructor is deprecated, but we need it for
    // compatibility.
    //noinspection deprecation
    mSoundPool = new SoundPool(MAX_SOUNDS, AudioManager.STREAM_MUSIC, 0);
    loadSounds();
}
 
源代码27 项目: crazyflie-android-client   文件: MainActivity.java
private void initializeSounds() {
    this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
    // Load sounds
    mSoundPool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
    mSoundPool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            mLoaded = true;
        }
    });
    mSoundConnect = mSoundPool.load(this, R.raw.proxima, 1);
    mSoundDisconnect = mSoundPool.load(this, R.raw.tejat, 1);
}
 
源代码28 项目: appinventor-extensions   文件: MediaUtil.java
/**
 * Loads the audio specified by mediaPath into the given SoundPool and
 * returns the sound id.
 *
 * Note that if the mediaPath is a content URI or an URL, the audio must be
 * copied to a temp file and then loaded from there. This could have
 * performance implications.
 *
 * @param soundPool the SoundPool
 * @param form the Form
 * @param mediaPath the path to the media
 */
public static int loadSoundPool(SoundPool soundPool, Form form, String mediaPath)
    throws IOException {
  MediaSource mediaSource = determineMediaSource(form, mediaPath);
  switch (mediaSource) {
    case ASSET:
      return soundPool.load(getAssetsIgnoreCaseAfd(form,mediaPath), 1);

    case REPL_ASSET:
      form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
      return soundPool.load(replAssetPath(mediaPath), 1);

    case SDCARD:
      form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
      return soundPool.load(mediaPath, 1);

    case FILE_URL:
      if (isExternalFileUrl(mediaPath)) {
        form.assertPermission(Manifest.permission.READ_EXTERNAL_STORAGE);
      }
      return soundPool.load(fileUrlToFilePath(mediaPath), 1);

    case CONTENT_URI:
    case URL:
      File tempFile = cacheMediaTempFile(form, mediaPath, mediaSource);
      return soundPool.load(tempFile.getAbsolutePath(), 1);

    case CONTACT_URI:
      throw new IOException("Unable to load audio for contact " + mediaPath + ".");
  }

  throw new IOException("Unable to load audio " + mediaPath + ".");
}
 
public void loadSounds() {
	// Sounds
	sounds = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
	biteSound = sounds.load(getContext(), R.raw.apple, 1);
	crashSound = sounds.load(getContext(), R.raw.crash, 1);
	appearSound = sounds.load(getContext(), R.raw.appear, 1);
}
 
源代码30 项目: mirror   文件: SoundManagerImpl.java
@Override
public void onPlugged(PluginBus bus) {
    super.onPlugged(bus);

    mSoundPool = new SoundPool.Builder().setAudioAttributes(
            new AudioAttributes.Builder()
                    .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                    .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                    .build()
    ).build();

    mAudioManager = D.get(AudioManager.class);
    mAcknowledgeId = mSoundPool.load(mAppManager.getAppContext(), R.raw.acknowledge, 1);
    mErrorId = mSoundPool.load(mAppManager.getAppContext(), R.raw.error, 1);
}
 
 类所在包
 类方法
 同包方法