2015-12-10 54 views
0

代码中是否有错误?getAssets()来自另一个类

它从我的主要活动和我的片段。但是,如果我在声音类中使用方法(loadSound),则getAssets()不起作用。

请帮我,任何想法? 谢谢!

这是我的片断代码:

public class CarnivoreFragment extends Fragment { 

    private int mCowSound; 
    private View view; 

    private ImageButton mCowImageButton; 


    public CarnivoreFragment() { 
    } 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, 
          Bundle savedInstanceState) { 

     view = inflater.inflate(R.layout.fragment_carnivore, container, false); 

     if (android.os.Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) { 

      Sound.createOldSoundPool(); 
     } else { 
      Sound.createNewSoundPool(); 
     } 

     mCowSound = Sound.loadSound("cow.wav"); 

     mCowImageButton = (ImageButton) view.findViewById(R.id.imageButtonCow); 
     mCowImageButton.setOnClickListener(onClickListener); 

     return view; 
    } 

    View.OnClickListener onClickListener = new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 
      switch (v.getId()) { 
       case R.id.imageButtonCow: 
        Sound.playSound(mCowSound); 
        Toast.makeText(view.getContext(), "Cow", Toast.LENGTH_SHORT).show(); 

        break; 

      } 
     } 
    }; 
} 

和我的“声音”类:

public class Sound { 

    private static SoundPool mSoundPool; 
    private static AssetManager mAssetManager; 
    private static int mStreamID; 
    private static Context context; 


    public Sound(Context context) { 
     this.context = context; 
    } 

    @TargetApi(Build.VERSION_CODES.LOLLIPOP) 
    public static void createNewSoundPool() { 
     AudioAttributes attributes = new AudioAttributes.Builder() 
       .setUsage(AudioAttributes.USAGE_GAME) 
       .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION) 
       .build(); 
     mSoundPool = new SoundPool.Builder() 
       .setAudioAttributes(attributes) 
       .build(); 
    } 

    @SuppressWarnings("deprecation") 
    public static void createOldSoundPool() { 
     mSoundPool = new SoundPool(3, AudioManager.STREAM_MUSIC, 0); 
    } 

    public static int playSound(int sound) { 
     if (sound > 0) { 
      mStreamID = mSoundPool.play(sound, 1, 1, 1, 0, 1); 
     } 
     return mStreamID; 
    } 

    public static int loadSound(String fileName) { 
     mAssetManager = context.getAssets(); 
     AssetFileDescriptor afd; 
     try { 
      afd = mAssetManager.openFd(fileName); 
     } catch (IOException e) { 
      e.printStackTrace(); 
       Toast.makeText(context, "Не могу загрузить файл " + fileName, 
        Toast.LENGTH_SHORT).show(); 
      return -1; 
     } 
     return mSoundPool.load(afd, 1); 
    } 


} 

回答

0

看起来好像你可能从来没有真正被设定,因为在你的Sound类上下文所有的调用似乎都是通过静态方法调用的。你有类在构造函数中设置上下文,但构造函数似乎不会被调用。

相关问题