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;
   }
}

そして、2 つのエラーが発生しています。最初のエラーは次のとおりです。

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) に表示され、2番目のエラーは次のとおりです。

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 が必要です。getSystemServiceContext インスタンスのメソッドですmyActivity.getSystemService()load()また、Context インスタンス (myActivity) を最初の引数として渡す必要があります。メイン アクティビティの外でコンテキストへの参照を保持することはお勧めできません。そのため、このロジックをアクティビティに戻すことを検討する必要があります。なぜシングルトンでこれをやろうとしているのですか? バックグラウンドで音楽を再生しますか?サービスをご利用ください。

于 2011-08-16T22:01:47.873 に答える
1

メソッドのロードには、 a のインスタンスが必要ですContext(つまり、 anActivityまたは a Service)。シングルトンにはそのインスタンスがないため、最初に のインスタンスを設定し、Contextその後でそのインスタンスを使用して load メソッドを呼び出す必要があります。

したがって、コンストラクターでこれを行うことはできません。

于 2011-08-16T22:02:08.207 に答える