gpt4 book ai didi

android - soundPool或Mediaplayer可获得短促的声音并需要帮助

转载 作者:行者123 更新时间:2023-12-02 22:56:53 25 4
gpt4 key购买 nike

我创建了一个简单的应用程序,在屏幕上只有几个按钮。其中一个按钮称为soundButton,当用户按下该按钮时,将播放音频文件。 (例如一个简单的词,例如“苹果”)。我有大约100个类似的屏幕,当我第一次播放声音时,我可以听到声音,过了一会儿,无论我转到哪个屏幕,我都再也听不到它们了(即使以前的屏幕也是如此)不再播放声音了)这是我的编码,仅供引用:

package com.example.main;

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;

public class EngApple extends Activity{

protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eng_apple);

ImageButton soundButton = (ImageButton) findViewById(R.id.sound);
final MediaPlayer mp1 = MediaPlayer.create(this, R.drawable.apple);


soundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
mp1.start();
}
});
}


}

这是一个声音很短的闪存卡应用程序。我读到,播放短声音所需的方法是使用soundPool。因此,我更改了代码,但徒劳无功。 (声音不播放)有人可以帮助我吗?谢谢

最佳答案

如果您确实确实按照上述模式进行了100多个 Activity ,则意味着每次启动新的“ Activity ”屏幕时,您都将实例化具有已加载声音的MediaPlayer实例。我怀疑通过同时具有多个MediaPlayer实例只会散发出一些东西。鉴于您的声音全在资源中,您可以将.create调用推迟到.start()调用之前。

考虑拥有一个仅管理MediaPlayer实例的单例类。类似于以下内容:

import android.content.Context;
import android.media.MediaPlayer;

public class MediaPlayerWrapper
{
static MediaPlayer _player;

public static void play(Context context, int id)
{
stop();
_player = MediaPlayer.create(context, id);
_player.start();
}

public static void stop()
{
if (_player != null)
{
_player.reset();
_player.release();
_player = null;
}
}
}

然后,您的onCreate方法变为:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.eng_apple);

soundButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
MediaPlayerWrapper.play(EngApple.this, R.drawable.apple);
}
});

关于android - soundPool或Mediaplayer可获得短促的声音并需要帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25599649/

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