简体   繁体   English

带有媒体播放器的应用程序无法正常运行

[英]App with media Player forces down

case R.id.btn7:
    if (mp != null && mp.isPlaying()) mp.stop();
    mp = MediaPlayer.create(a.this, R.raw.aaaa);
    mp.start();
    break;
case R.id.btn8:
    if (mp != null && mp.isPlaying()) mp.stop();
    mp = MediaPlayer.create(a.this, R.raw.bbbb);
    mp.start();
    break;

How could I use setDataSource in order to stop my app for force close? 我如何使用setDataSource来停止我的应用程序强制关闭? Please help! 请帮忙! If I use it like this, eclipse highlights red the setDataSource; 如果我这样使用,eclipse将红色突出显示setDataSource;

public void onClick(View v) {
    switch(v.getId()) {
        case R.id.btn:
            if (mp != null && mp.isPlaying()) mp.stop();
            mp.setDataSource(zoo.this,R.raw.gata);
            mp.prepare();
            mp.start();
            break;

Okay, so I've actually been working on something similar for a hobby project I've been working on. 好的,所以我实际上一直在为自己正在从事的一项业余项目从事类似工作。 After reading through the MediaPlayer documentation for a while, here is the method I've come up with (note that this is with the intention of having only a single sound playing at one time): 在阅读了一段时间的MediaPlayer文档之后,这是我想出的方法(请注意,这是为了一次只播放一个声音):

First, I created an overridden Application class to hold my global variables -- in this instance, my single MediaPlayer object: 首先,我创建了一个重写的Application类来保存我的全局变量-在这种情况下,是我的单个MediaPlayer对象:

public class GlobalVars extends Application {
    private static MediaPlayer mp = new MediaPlayer();

    public static MediaPlayer getMediaPlayer() {
        return mp;
    }
}

This creates one instance of a MediaPlayer once the application begins. 一旦应用程序启动,这将创建一个MediaPlayer实例。 It's also static, so it's available without having to instantiate the class. 它也是静态的,因此无需实例化类即可使用。

Now, in my main class (particularly in my onClick method), I retrieve this instance, reset it, set my data source, prepare it for play, and then start it: 现在,在我的主类中(尤其是在我的onClick方法中),我检索此实例,将其重置,设置数据源,为播放做准备,然后启动它:

MediaPlayer mp = GlobalVars.getMediaPlayer();

//note that in my case, item is an object of mine that 
//contains an AssetFileDescriptor, which you can get by
//calling getAssets().openFd("filename.mp3");
AssetFileDescriptor afd = item.getDescriptor();

mp.reset();
//leaving out the try/catch block for conciseness
mp.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mp.prepare();
mp.start();

you can use sound manager if you finite no. 如果您没有限制,则可以使用声音管理器。 of sounds to play. 播放声音。 http://developer.android.com/reference/android/media/AudioManager.html http://developer.android.com/reference/android/media/AudioManager.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM