jjzjj

android soundpool堆大小溢出

coder 2023-11-30 原文

我在 Debug 中运行时出现数百次此错误,它似乎不影响程序,但我如何摆脱它?

根据其他帖子我知道可以追溯到SoundPool

09-15 09:03:09.190:错误/AudioCache(34):堆大小溢出!请求大小:1052672,最大大小:1048576

最佳答案

SoundPool 将所有加载文件的缓冲区大小硬编码为 1M。因此,当您将太多文件加载到 SoundPool 中时,您可能会遇到“堆大小溢出”错误。我在将游戏声音 FX 加载到 SoundPool 的游戏项目中也遇到了这个问题,解决方案如下:

  1. 在 MediaPlayer 中播放长/大背景音乐。
  2. 在多个 SoundPool 实例中播放短声音文件以防止堆错误。多 SoundPools 的示例代码:


 /**
  * Multi SoundPool to prevent memory error.
  */
public class SoundPools {<p></p>

  private static final String TAG = "SoundPools";

  private static final int MAX_STREAMS_PER_POOL = 15;

  private List<SoundPoolContainer> containers;

  public SoundPools() {
    containers = Collections.synchronizedList(new ArrayList<SoundPoolContainer>());
  }

  public void loadSound(Context context, String id, String file) {
    Log.d(TAG, "SouldPools load sound " + file);
    try {
      for (SoundPoolContainer container : containers) {
        if (container.contains(id)) {
          return;
        }
      }
      for (SoundPoolContainer container : containers) {
        if (!container.isFull()) {
          container.load(context, id, file);
          return;
        }
      }
      SoundPoolContainer container = new SoundPoolContainer();
      containers.add(container);
      container.load(context, id, file);
    } catch (Exception e) {
      Log.w(TAG, "Load sound error", e);
    }
  }

  public void playSound(Context context, String id, String file) {
    Log.d(TAG, "SouldPools play sound " + file);
    try {
      for (SoundPoolContainer container : containers) {
        if (container.contains(id)) {
          container.play(context, id, file);
          return;
        }
      }
      for (SoundPoolContainer container : containers) {
        if (!container.isFull()) {
          container.play(context, id, file);
          return;
        }
      }
      SoundPoolContainer container = new SoundPoolContainer();
      containers.add(container);

      container.play(context, id, file);
    } catch (Exception e) {
      Log.w(TAG, "Play sound error", e);
    }
  }

  public void onPause() {
    for (SoundPoolContainer container : containers) {
      container.onPause();
    }
  }

  public void onResume() {
    for (SoundPoolContainer container : containers) {
      container.onResume();
    }
  }

  private static class SoundPoolContainer {
    SoundPool soundPool;
    Map<String, Integer> soundMap;
    AtomicInteger size;

    public SoundPoolContainer() {
      this.soundPool = new SoundPool(MAX_STREAMS_PER_POOL, android.media.AudioManager.STREAM_MUSIC, 0);
      this.soundMap = new ConcurrentHashMap<String, Integer>(MAX_STREAMS_PER_POOL);
      this.size = new AtomicInteger(0);
    }

    public void load(Context context, String id, String file) {
      try {
        this.size.incrementAndGet();
        soundMap.put(id, soundPool.load(context.getAssets().openFd(file), 1));
      } catch (Exception e) {
        this.size.decrementAndGet();
        Log.w(TAG, "Load sound error", e);
      }
    }

    public void play(Context context, String id, String file) {
      android.media.AudioManager audioManager = (android.media.AudioManager) context
          .getSystemService(Context.AUDIO_SERVICE);
      final int streamVolume = audioManager.getStreamVolume(android.media.AudioManager.STREAM_MUSIC);
      Integer soundId = soundMap.get(id);
      if (soundId == null) {
        soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
          @Override
          public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPool.play(sampleId, streamVolume, streamVolume, 1, 0, 1f);
          }
        });
        try {
          this.size.incrementAndGet();
          soundPool.load(context.getAssets().openFd(file), 1);
        } catch (IOException e) {
          this.size.decrementAndGet();
          Log.w(TAG, "Load/Play sound error", e);
        }
      } else {
        try {
          soundPool.play(soundId, streamVolume, streamVolume, 1, 0, 1f);
        } catch (Exception e) {
          Log.w(TAG, "Play sound error", e);
        }
      }
    }

    public boolean contains(String id) {
      return soundMap.containsKey(id);
    }

    public boolean isFull() {
      return this.size.get() >= MAX_STREAMS_PER_POOL;
    }

    public void onPause() {
      try {
        soundPool.autoPause();
      } catch (Exception e) {
        Log.w(TAG, "Pause SoundPool error", e);
      }
    }

    public void onResume() {
      try {
        soundPool.autoResume();
      } catch (Exception e) {
        Log.w(TAG, "Resume SoundPool error", e);
      }
    }
  }

}

关于android soundpool堆大小溢出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7428448/

有关android soundpool堆大小溢出的更多相关文章

  1. ruby-on-rails - 在 Rails 中将文件大小字符串转换为等效千字节 - 2

    我的目标是转换表单输入,例如“100兆字节”或“1GB”,并将其转换为我可以存储在数据库中的文件大小(以千字节为单位)。目前,我有这个:defquota_convert@regex=/([0-9]+)(.*)s/@sizes=%w{kilobytemegabytegigabyte}m=self.quota.match(@regex)if@sizes.include?m[2]eval("self.quota=#{m[1]}.#{m[2]}")endend这有效,但前提是输入是倍数(“gigabytes”,而不是“gigabyte”)并且由于使用了eval看起来疯狂不安全。所以,功能正常,

  2. HBase Region 简介和建议数量&大小 - 2

    Region是HBase数据管理的基本单位,region有一点像关系型数据的分区。region中存储这用户的真实数据,而为了管理这些数据,HBase使用了RegionSever来管理region。Region的结构hbaseregion的大小设置默认情况下,每个Table起初只有一个Region,随着数据的不断写入,Region会自动进行拆分。刚拆分时,两个子Region都位于当前的RegionServer,但处于负载均衡的考虑,HMaster有可能会将某个Region转移给其他的RegionServer。RegionSplit时机:当1个region中的某个Store下所有StoreFile

  3. ruby-on-rails - Ruby 中意外的大小写行为 - 2

    我在一段非常简单的代码(如我所想)中得到了一个错误的值:org=4caseorgwhenorg=4val='H'endputsval=>nil请不要生气,我希望我错过了一些非常明显的东西,但我真的想不通。谢谢。 最佳答案 这是典型的Ruby错误。case有两种被调用的方法,一种是你传递一个东西作为分支的基础,另一种是你不传递的东西。如果您确实在case中指定了一个表达式语句然后评估所有其他条件并与===进行比较.在这种情况下org评估为false和org===false显然不是真的。所有其他情况也是如此,它们要么是真的,要么是假的。

  4. ruby - 改变替换的大小写 - 2

    我有以下内容:text.gsub(/(lower)(upper)/,'\1\2')我可以将\2替换为大写吗?类似于:sed-e's/\(abc\)/\U\1/'这在Ruby中可行吗? 最佳答案 查看gsub文档:str.gsub(模式){|匹配|block}→new_str在block形式中,当前匹配字符串作为参数传入,$1、$2、$`、$&、$'等变量将被适当设置。block返回的值将替换为每次调用的匹配项。"alowerupperb".gsub(/(lower)(upper)/){|s|$1+""+$2.upcase}

  5. ruby - Sinatra:哈希的未定义方法字节大小 - 2

    很难说出这里要问什么。这个问题模棱两可、含糊不清、不完整、过于宽泛或夸夸其谈,无法以目前的形式得到合理的回答。如需帮助澄清此问题以便重新打开,visitthehelpcenter.关闭9年前。我正在创建一个Sinatra应用程序,它采用上传的CSV文件并将其内容放入哈希中。当我像这样在我的app.rb中引用这个散列时:hash=extract_values(path_to_filename)我不断收到此错误消息:undefinedmethod`bytesize'forHash:0x007fc5e28f2b90#object_idfile:utils.rblocation:bytesiz

  6. ruby - 使2个数组大小相同 - 2

    2个数组的数组:a=[[1,2],[22,11],[18,9]]b=[[1,81]]用[0,0]填充第二个的最佳方法是什么,以便它们具有相同的大小? 最佳答案 b.fill(b.size..a.size-1){[0,0]} 关于ruby-使2个数组大小相同,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/29725615/

  7. ruby - 数组大小太大 - ruby - 2

    我收到“ArgumentError:数组大小太大”消息,代码如下:MAX_NUMBER=600_000_000my_array=Array.new(MAX_NUMBER)问题。Array.new函数在Ruby中的最大值是多少? 最佳答案 具有5亿个元素的数组的大小为2GiBytes,这取决于您使用的特定操作系统,通常是一个进程可以处理的最大值。换句话说:您的数组大于您的地址空间。因此,解决方案很明显:要么缩小数组(例如,将其分成block),要么扩大地址空间(在Linux中,您可以修补内核以获得3、3.5甚至4GiByte地址空间,

  8. ruby-on-rails - Rails 存在吗?不区分大小写 - 2

    Model.exists?("lower(email)=?",params[:email].downcase)返回错误:ArgumentError(参数数量错误(2代表0..1)):是否可以使用不区分大小写的匹配来执行exists?? 最佳答案 您需要做的就是:Model.exists?(["lower(email)=?",params[:email].downcase])它正在寻找一个参数,但您提供了两个。使用数组形式和查找式条件应该可以满足您的需求。 关于ruby-on-rails-

  9. ruby - 使用 Ruby 在数组中查找大小为 N 的所有子集 - 2

    给定一个数组['a','b','c','d','e','f'],我如何获得包含两个的所有子集的列表、三、四元素?我是Ruby的新手(从C#迁移过来),不确定“Ruby之道”是什么。 最佳答案 查看Array#combination然后是这样的:2.upto(4){|n|array.combination(n)} 关于ruby-使用Ruby在数组中查找大小为N的所有子集,我们在StackOverflow上找到一个类似的问题: https://stackoverf

  10. ruby - == 和大小写的区别? - 2

    我是Ruby的新手,正在尝试解决让我感到困惑的问题。在编写一个简单的解析器时,我发现将char与==进行比较与将其与case表达式进行比较会产生不同的结果:File.open('Quote.txt')do|f|f.chars.eachdo|c|putsc=='"'?'Quote':'Err'putscasecwhen'"'then'QuoteCase'else'ErrCase'endpc=='"',c==='"',cendend假设Quote.txt是一个包含单引号字符(0x22)的1字节文件,这将产生:QuoteErrCasetruetrue"\""我假设我做错了什么,但我无法弄清楚

随机推荐