开发者

mediaplayer dies android

i have a little problem with the media player class. I have a button, and开发者_StackOverflow by pressing it a sound will be played. The thing is that there is some delay between when i press the button and when the sound is played, and if i press it too many times the media player dies, and then no sound is played at all and i get the following errors:

ERROR/MediaPlayer(3960): error (-19, 0)
ERROR/AudioTrack(3931): AudioFlinger could not create track, status: -12
ERROR/AudioSink(3931): Unable to create audio track

Here's the code:

Button b = (Button)findViewById(R.id.button);
        b.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                AssetFileDescriptor afd;
                try {

                    afd = getAssets().openFd("bassdrum6.mp3");
                    player = new MediaPlayer();
                    player.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
                    player.prepare();
                    player.start();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

I don't know what's wrong here. I need some help.

Thanks in advance.


Probably because you are creating multiple MerdiaPlayer objects at the same time (I would expect Android API code should be able to handle this neatly). Anyways, You can build a check in your code to validate if mediaplayer is already created. See for a good example: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/media/MediaPlayerDemo_Video.html

Also, it would be better to extend your implementation to release the mediaplayer whenever it has completed it's job. something like a cleanup where afterwards the objects are released.


Your going to want to use an on touch listener if you want it to play while the button is being pressed

Button b = (Button)findViewById(R.id.button);
b.setOnTouchListener(new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        if (global.toggleOnOff == false) {

            if (event.getAction() == MotionEvent.ACTION_DOWN) {
               //what you want to happen when they touch the button
            }
            else if(event.getAction() == MotionEvent.ACTION_UP) {
               //what you want to happen when they let go of the button
            }
        }

        return false;
    }
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜