java - 我的 soundpool 项目无法正常播放?

标签 java android soundpool

我一直在尝试实现这个 soundpool 类(在教程的一些帮助下),但是当我尝试在虚拟设备上运行它时,声音不会播放... main_activity XML 文件加载正常,但是预计加载时会播放声音。

这是源代码。

public class MainActivity extends Activity {

private SoundPool soundpool;
private boolean soundPoolLoaded = false;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Create a new SoundPool instance.
    // 2 = number of sounds that can be simultaneously played
    // AudioManager.STREAM_MUSIC = The type of sound stream. STREAM_MUSIC is the most common one
    // 0 = sound quality, default is 0.
    // setOnLoadCompleteListener loads the file 
    soundpool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
    soundpool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
        @Override
        public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
            soundPoolLoaded = true;
        }
    });

    playSound("car_phonic");
}


// This method will load a sound resource from the res/raw folder by the input name given as a string (soundName).
// If the sound resource is found by name, it will attempt to play the sound
// soundPoolLoaded value becomes true when the file is fully loaded
public void playSound(String soundName) {
    if(soundPoolLoaded == true)
    {
        // Get the current context resources and find the correct sound resource for playing the sound
        Resources res = this.getResources();
        int soundId = 0;
        soundId = res.getIdentifier(soundName, "raw", this.getPackageName());

        if(soundId != 0){   
        soundpool.play(soundId, 1, 1, 0, 0, 1);
        }


        SystemClock.sleep(500);
        playSound(soundName);

    }
    }
}

如有任何帮助,我们将不胜感激!

最佳答案

  • play() 采用 SoundPools load() 返回的 soundID,而不是通用的 Android 资源 ID
  • 调用onLoadComplete,然后声音文件完成加载,注意sampleId参数

所以,它的基本形式是:

soundpool.setOnLoadCompleteListener(new OnLoadCompleteListener() {
    @Override
    public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
        soundpool.play(sampleId, 1, 1, 0, 0, 1);
    }
});

soundpool.load(this, R.raw.car_phonic, 0);

请注意,SoundPool 在后台加载数据,因此样本无法立即可用。

关于java - 我的 soundpool 项目无法正常播放?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16072117/

相关文章:

java - 根据 Combobox 中的选定索引动态更新数据库中的值

java - 下拉框 - 从 Spring MVC 模型/上下文到使用 freemarker 的表单

android 将媒体数据传递给另一个 Activity

android - 如何在soundPool(Android)中逐渐加载声音?

android - Soundpool 只播放文件的前 5 秒。为什么?

java - 是否有 CFHTTP 的 Java 替代品来使用 ColdFusion 的 NTLM 身份验证?

java - JSON数据问题

android - 如何在候选 View 上显示候选 View 和回收器选项卡 View 位置?

android - 从当前应用程序加载另一个应用程序

android - Galaxy Nexus 上的 OGG 解码速度极慢