在onDraw上播放声音

时间:2013-03-09 10:06:46

标签: android android-mediaplayer

我想在比赛期间播放声音。 但是当我启动应用程序时,声音每次只播放半秒钟。

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Shapes shapes = new Shapes(this);
    setContentView(shapes);
    MediaPlayer mp = MediaPlayer.create(this, R.raw.back);
    try {
        mp.prepare();
    } catch (IllegalStateException e) {}
      catch (IOException e) {}
    mp.start();
    mp.setLooping(true);
}

mp.setLooping(true)没有帮助,它只在我删除“setContentView(shapes);”时才有效。 我能做些什么,声音在半秒后没有停止?

4 个答案:

答案 0 :(得分:0)

如果声音很短,请添加循环

mp.setLooping(true);

另外,您在标题中提到了onDraw()方法,但您提供的gove来自onCreate()

答案 1 :(得分:0)

你可以使用setLooping(true) http://developer.android.com/reference/android/media/MediaPlayer.html#setLooping(boolean)

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Shapes shapes = new Shapes(this);
        setContentView(shapes);
        MediaPlayer mp = MediaPlayer.create(this, R.raw.back);
        try {
            mp.prepare();
        } catch (IllegalStateException e) {}
          catch (IOException e) {}
        mp.setLooping(true);
        mp.start();
    }

答案 2 :(得分:0)

您的MediaPlayer对象(mp)在mp.start();

时播放一次

如果您不断播放,请添加setLooping(true)

MediaPlayer mp = MediaPlayer.create(this, R.raw.back);
try {
    mp.prepare();
    mp.setLooping(true);
    mp.start();
} catch (IllegalStateException e) { 
    e.printStackTrace();
} catch (IOException e) {
   e.printStackTrace();
}

答案 3 :(得分:0)

如果这是一个游戏,我假设它在一个线程中运行。 你的游戏是在一个线程中运行的吗?

你的线程应该有一个doStart()或类似的方法,已经声明了MediaPlayer。

在游戏主题中启动背景音乐的截断基本示例:

boolean BGMisOn; MediaPlayer BGM;

DOSTART() { ... ... 如果(BGMisOn)BGM.start() ... ... }

相关问题