且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

完成播放后,如何释放媒体播放器?

更新时间:2023-02-02 16:05:36

我发表了评论,但我将发布答案以表明我的意思...

I left a comment, but I'll post an answer to show what I mean anyway...

这个想法是您可以使用一定数量的MediaPlayer实例.这样,您就永远不会超过最大实例数.数组应为您希望能够听到的并发声音的长度.如果声音是本地文件,则准备声音所需的时间几乎可以忽略不计,因此在单击处理程序中调用create不会导致糟糕的性能.我想您的每个按钮都与一个特定的资源相关联,所以我设置了一个辅助方法,以相同的方式为每个按钮创建和播放声音.

The idea is that you have a set number of MediaPlayer instances that you can use. That way you never exceed the maximum number of instances. The array should be the length of the number of concurrent sounds you expect to be able to hear. If the sounds are local files, the length of time it takes to prepare the sounds should be almost negligible, so calling create inside the click handler should not result in terrible performance. Each of your buttons is associated with a particular resource, I suppose, so I set up a helper method to create and play the sounds for each button in the same way.

public class soundPageOne extends Activity {

    private MediaPlayer[] mPlayers = new MediaPlayer[2];
    private int mNextPlayer = 0;

    @Override
    public void onCreate(Bundle savedState) {
        super.onCreate(savedState);
        setContentView(R.layout.soundsone);
        Button playSound1 = (Button)this.findViewById(R.id.peter1Button);
        playSound1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startSound(R.raw.peter1);
            }
        });
    }

    public void onDestroy() {
        super.onDestroy(); // <---------------------- This needed to be there
        for (int i = 0; i < mPlayers.length; ++i)
            if (mPlayers[i] != null)
                try {
                    mPlayers[i].release();
                    mPlayers[i] = null;
                }
                catch (Exception ex) {
                    // handle...
                }
    }

    private void startSound(int id) {
        try {
            if (mPlayers[mNextPlayer] != null) {
                mPlayers[mNextPlayer].release();
                mPlayers[mNextPlayer] = null;
            }
            mPlayers[mNextPlayer] = MediaPlayer.create(this, id);
            mPlayers[mNextPlayer].start();
        }
        catch (Exception ex) {
            // handle
        }
        finally {
            ++mNextPlayer;
            mNextPlayer %= mPlayers.length;
        }
    }

}