Android,无法让 MediaPlayer 类工作

发布于 2024-12-01 04:55:02 字数 982 浏览 1 评论 0原文

我想为我创建的动画添加声音。每次动画开始时,据说声音也必须开始,但我无法启动声音。

动画一切正常,这是代码片段:

public class TestActivity extends Activity {
AnimationDrawable  anim;
MediaPlayer mp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    playAnimation(R.id.frameLayout1,R.drawable.anim2,R.raw.bang);
}

public void playAnimation(int FrameLayoutAddress, int animationXMLAdress, int soundAddress)
{
     mp = MediaPlayer.create(this.getApplicationContext(), soundAddress);
     mp.start(); // error here

     FrameLayout imgView = (FrameLayout)findViewById(FrameLayoutAddress);
     imgView.setBackgroundResource(animationXMLAdress);
     anim = (AnimationDrawable) imgView.getBackground();
     imgView.post(new Runnable()
     {       
         @Override
         public void run()
         {
             anim.start();

         }
     });    
}   

}

任何人都可以指出我的错误吗?预先感谢您的宝贵时间。

I would like to add sound to an animation that I have created. Everytime the animation starts, supposedly a sound has to start as well, but I can't manage to start the sound.

All is ok with the animation, here's the code piece:

public class TestActivity extends Activity {
AnimationDrawable  anim;
MediaPlayer mp;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    playAnimation(R.id.frameLayout1,R.drawable.anim2,R.raw.bang);
}

public void playAnimation(int FrameLayoutAddress, int animationXMLAdress, int soundAddress)
{
     mp = MediaPlayer.create(this.getApplicationContext(), soundAddress);
     mp.start(); // error here

     FrameLayout imgView = (FrameLayout)findViewById(FrameLayoutAddress);
     imgView.setBackgroundResource(animationXMLAdress);
     anim = (AnimationDrawable) imgView.getBackground();
     imgView.post(new Runnable()
     {       
         @Override
         public void run()
         {
             anim.start();

         }
     });    
}   

}

Can anyone point out my mistake ? Thanks in advance for your time.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

慢慢从新开始 2024-12-08 04:55:02

您应该在 mp.start() 之前调用 mp.prepare()。另外,建议在调用 mp.prepare() 之前重置 MediaPlayer

You should call mp.prepare() before mp.start(). Also it's suggested to reset the MediaPlayer before calling mp.prepare().

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文