当前位置: 移动技术网 > IT编程>移动开发>Android > Android使用SoundPool播放短音效

Android使用SoundPool播放短音效

2020年03月09日  | 移动技术网IT编程  | 我要评论

漆雾净化设备,百姓网徐州,囧的呼唤99

前言

对于android播放一些简短音效,例如提示音,或者铃声,相对于使用mediaplayer,soundpool可以节省更多资源,并且可以同时播放多个音效,而且可以针对不同音效设置不同播放品质

实现

soundpool的具体作用,就不再阐述,直接贴代码

private soundpool.builder spbuilder;
private soundpool soundpool;
private integer[] fmsound = fmmanager.getrawaudios();

 if (build.version.sdk_int >= build.version_codes.lollipop) {
      if (null == spbuilder) {
        spbuilder = new soundpool.builder();
        audioattributes.builder builder = new audioattributes.builder();
        builder.setlegacystreamtype(audiomanager.stream_music);
        spbuilder.setaudioattributes(builder.build());
        spbuilder.setmaxstreams(10);
      }
      if (null == soundpool) {
        soundpool = spbuilder.build();
      }
    } else {
      if (null == soundpool) {
        soundpool = new soundpool(10, audiomanager.stream_music, 10); //最多播放10个音效,格式为steam_music,音质为10
      }
    }
    soundpool.setonloadcompletelistener(this);
    if (null == fmarray) {
      fmarray = new sparseintarray();
    }
    if (null == streamarray) {
      streamarray = new sparseintarray();
    }
    for (int i = 0; i < fmsound.length; i++) {
      fmarray.put(i + 1, soundpool.load(this, fmsound[i], 1));  //将需要播放的资源添加到soundpool中,并保存返回的streamid,通过streamid可以停止某个音效
    }


 private void playfmbyposition(int resultid) {
    if (null == soundpool || resultid < 0 || fmarray == null || fmarray.size() < 0 || streamarray == null)
      return;
    logutils.e(resultid + "------------" + fmarray.size());

    if (resultid < fmarray.size()) {
      if (!fmplaying.isplay(resultid)) {
        int fmplayid = soundpool.play(fmarray.get(resultid + 1), 1, 1, 0, -1, 1);
        streamarray.put(resultid, fmplayid);
        fmplaying.setplay(resultid, true);
      } else {
        soundpool.stop(streamarray.get(resultid));
        streamarray.removeat(resultid);
        fmplaying.setplay(resultid, false);
      }
    }
  }

  static class fmplaying {
    private static sparsebooleanarray playarray = new sparsebooleanarray();

    public static boolean isplay(int position) {
      return playarray.get(position, false);
    }

    public static void setplay(int position, boolean play) {
      playarray.put(position, play);
    }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网