【问题标题】:Android Soundpool Load(String path, int priority)Android Soundpool 加载(字符串路径,int 优先级)
【发布时间】:2012-08-23 14:49:04
【问题描述】:

我正在尝试从 android 加载声音。 声音在res/raw/myownsound.wav 之下。 我知道我已经可以使用以下方法加载声音了:

 soundPool.load(context, R.raw.myownsound, 1)

出于自定义目的,我想使用以下方式加载它:

 soundPool.load("res/raw/myownsound", 1)

...但我收到以下错误:error loading res/raw/myownsound。 我还尝试了以下方法:

 soundPool.loadSound("android.resource://upg.GraphismeBase/raw/myownsound", 1)

.. 但我也收到一个错误:error loading android.resource://upg.GraphismeBase/raw/myownsound

soundPool.load(path, priority) 的正确使用方法是什么?

【问题讨论】:

    标签: android audio resources soundpool


    【解决方案1】:

    在您的项目中创建文件夹结构

    /assets/sounds/data/
    

    然后将你的 wav 文件复制到那里。

    // Declare globally if needed
    int mySoundId;
    SoundPool soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0 );
    AssetManager am = this.getAssets();
    
    //Use in whatever method is used to load the sounds
    try {
        mySoundId = soundPool.load(am.openFd("sounds/data/myownsound"), 1);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    

    可以试试这个(不确定它是否有效):

    SoundPool mySoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
        int myAudioFile = getResId("claps", R.raw.class);
        try{
            mySoundPool.load(context.getActivity(),myAudioFile,1);
        } catch (Exception e){
            message = String.valueOf(e);
        }
    
    public static int getResId(String variableName, Class<?> c) {
        Field field = null;
        int resId = 0;
        try {
            field = c.getField(variableName);
            try {
                resId = field.getInt(null);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return resId;
    }
    

    【讨论】:

    • 嗯,这肯定是一个可行的答案,但我真的很想在这里知道如何使用纯路径版本,而不是 FileDescriptor 版本。
    • 我放了第二种方法,可能这就是你想要的
    • 在哪里导入 Field 类?
    【解决方案2】:

    使用名为mContext 的上下文的简单工作方式。 它通过在运行时获取标识符 id 按名称加载资源。

    int sound_id = mContext.getResources().getIdentifier("myownsound", "raw",
                                                         mContext.getPackageName());
    soundPool.load(mContext, sound_id, 1);
    

    它还可以加载drawables或xml文件,例如将"raw"替换为"drawable""xml"

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-05-15
      • 1970-01-01
      • 1970-01-01
      • 2022-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多