0

注意:我是个菜鸟,所以真的不知道这些错误是什么意思。

这是我的课程代码:

package ryan.test;

import java.util.HashMap;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class MySingleton {

    private MySingleton instance;

    private static SoundPool mSoundPool;
    private HashMap<Integer, Integer> soundPoolMap;

    public static final int A1 = 1;

    private MySingleton() {
        mSoundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);// Just an example
        soundPoolMap = new HashMap<Integer, Integer>();
        soundPoolMap.put(A1, mSoundPool.load(this, R.raw.a,    1));
   //   soundPoolMap.put(A5, mSoundPool.load(MyApp.this,       R.raw.a,    1));
    }

    public synchronized MySingleton getInstance() {
        if(instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }

    public void playSound(int sound) {
        AudioManager mgr = (AudioManager)MySingleton.getSystemService(Context.AUDIO_SERVICE);
        float streamVolumeCurrent = mgr.getStreamVolume(AudioManager.STREAM_MUSIC);
        float streamVolumeMax = mgr.getStreamMaxVolume(AudioManager.STREAM_MUSIC);    
        float volume = streamVolumeCurrent / streamVolumeMax;

        mSoundPool.play(soundPoolMap.get(sound), volume, volume, 1, 0, 1f);     
    }

    public SoundPool getSoundPool() {
        return mSoundPool;
   }
}

我收到两个错误,第一个错误在这里:

soundPoolMap.put(A1, mSoundPool.load(this, R.raw.a,    1));

并且错误说The method load(Context, int, int) in the type SoundPool is not applicable for the arguments (MySingleton, int, int) 第二个错误在这里:

AudioManager mgr = (AudioManager)MySingleton.getSystemService(Context.AUDIO_SERVICE);

错误说The method getSystemService(String) is undefined for the type MySingleton

4

3 回答 3

2

除非您传入 applicationContext 或活动,否则您无法访问非活动类中的系统服务。您需要在extends Activity课堂上执行此代码。

您需要在构造函数中包含上下文才能访问声音提供者提供的服务,或者传入声音提供者管理对象以访问这些对象。

代码应该很简单,只需在您的类中声明一个 SoundPool 对象并将其传递给构造函数即可。

于 2011-08-16T22:02:59.267 回答
1

您需要一个 Context 才能使用这些方法。getSystemService是 Context 实例的一个方法,myActivity.getSystemService(). load()还希望您将 Context 实例 (myActivity) 作为第一个参数传递。不建议您在主活动之外保留对上下文的引用,因此您应该考虑将此逻辑移回活动中。你为什么要在单例中这样做?在后台播放音乐?使用服务。

于 2011-08-16T22:01:47.873 回答
1

方法 load 需要 a 的实例Context(即 anActivity或 a Service)。由于您的单例没有该实例,因此您需要首先设置 的实例Context,然后才使用该实例调用 load 方法。

因此,您不能在构造函数中执行此操作。

于 2011-08-16T22:02:08.207 回答