gpt4 book ai didi

SoundPool 上的 android 空引用?

转载 作者:行者123 更新时间:2023-11-29 02:04:27 24 4
gpt4 key购买 nike

当我尝试通过我的 Android 聊天应用程序播放声音时,我收到了一个 null 引用。每次协议(protocol)字符串中出现微笑时,我都想播放音频。我的声音文件是 OGG 格式,位于 res->raw->mysound.ogg 中。

我的 Android 类中有以下 SoundManager 类:

package chatclient.utility;

import java.util.HashMap;
import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

public class SoundManager {

private SoundPool mSoundPool;
private HashMap<Integer, Integer> mSoundPoolMap;
private AudioManager mAudioManager;
private Context mContext;


public SoundManager()
{

}

public void initSounds(Context theContext) {
mContext = theContext;
mSoundPool = new SoundPool(4, AudioManager.STREAM_MUSIC, 0);
mSoundPoolMap = new HashMap<Integer, Integer>();
mAudioManager = (AudioManager)mContext.getSystemService(Context.AUDIO_SERVICE);
}

public void addSound(int Index,int SoundID)
{
mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1));
}

public void playSound(int index) {

int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, 0, 1f);
}

public void playLoopedSound(int index) {

int streamVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
mSoundPool.play(mSoundPoolMap.get(index), streamVolume, streamVolume, 1, -1, 1f);
}

这是我在主类中调用它的代码:

在我的 onCreate 中:

    mSoundManager = new chatclient.utility.SoundManager();
mSoundManager.initSounds(getBaseContext());

mSoundManager.addSound(1, R.raw.bigsmilesmiley ); //:D
mSoundManager.addSound(2, R.raw.smilesmiley ); //:)
mSoundManager.addSound(3, R.raw.tonguesmiley ); //:P
mSoundManager.addSound(4, R.raw.confusedsmiley ); //:S
mSoundManager.addSound(5, R.raw.ofacesmiley ); //:O
mSoundManager.addSound(6, R.raw.sadsmiley); //:(

然后调用它:

if (pollServerResult.contains(":)")) {                
mSoundManager.playSound(2);
} else if (pollServerResult.contains(":D)")) {
mSoundManager.playSound(1);
} else if (pollServerResult.contains(":P")) {
mSoundManager.playSound(3);
} else if (pollServerResult.contains(":S")) {
mSoundManager.playSound(4);
} else if (pollServerResult.contains(":O")) {
mSoundManager.playSound(5);
} else if (pollServerResult.contains(":(")) {
mSoundManager.playSound(6);
}

唯一的问题是,当有人发布其中一张面孔时,我得到一个 null 引用。

最佳答案

改变这个:

public void addSound(int Index,int SoundID) {
mSoundPoolMap.put(1, mSoundPool.load(mContext, SoundID, 1));
}

有了这个:

public void addSound(int Index,int SoundID) {
mSoundPoolMap.put(Index, mSoundPool.load(mContext, SoundID, 1));
}

关于SoundPool 上的 android 空引用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10844652/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com