仅创建一个Media Player

时间:2015-05-19 21:23:34

标签: android audio media-player instance android-mediaplayer

我在网页视图中播放声音文件,用Javascript调用它们。

这是我使用的代码,但每当我将新声音称为mediaplayer的实例时,它就会创建,因此我无法停止播放声音并且有太多的媒体播放器在运行。

public class AudioInterface {
    Context mContext;

    AudioInterface(Context c) {
        mContext = c;
    }

    //Play an audio file from the webpage
    @JavascriptInterface
    public void playAudio(String aud) {
        final MediaPlayer mp;
        try {
            AssetFileDescriptor fileDescriptor =
                    mContext.getAssets().openFd(aud);

            mp = new MediaPlayer();
            mp.setDataSource(fileDescriptor.getFileDescriptor(),
                fileDescriptor.getStartOffset(),
                fileDescriptor.getLength());
            fileDescriptor.close();
            mp.prepare();
            mp.start();
        }

        catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
};

如何只创建mediaplayer的一个实例,以便在播放新声音之前停止当前声音?

1 个答案:

答案 0 :(得分:0)

用此替换您的代码。请注意我如何在playAudio(...)之外初始化MediaPlayer:

public class AudioInterface {

    Context mContext;
    final MediaPlayer mp;

    AudioInterface(Context c) {
        mContext = c;
        mp = new MediaPlayer();
    }

    // Play an audio file from the webpage
    @JavascriptInterface
    public void playAudio(String aud) {

        try {
            AssetFileDescriptor fileDescriptor = mContext.getAssets().openFd(aud);

            mp.reset();
            mp.setDataSource(fileDescriptor.getFileDescriptor(), fileDescriptor.getStartOffset(), fileDescriptor.getLength());
            fileDescriptor.close();
            mp.prepare();
            mp.start();
        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalStateException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}