简体   繁体   English

Mediaplayer声音不重叠

[英]Mediaplayer sound does not overlap

When you click the button it adds 5 to a sum and makes a sound. 当您单击按钮时,它会将5加到总和并发出声音。 The problem is that when you click it repeatedly, it adds 5 but the sound does not overlap. 问题在于,当您反复单击它时,它会增加5,但声音不会重叠。

Please see code below: 请参见下面的代码:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_basic_2);

    final MediaPlayer plussound = MediaPlayer.create(basic_2.this, R.raw.plus);    

    Button plus5b = (Button)findViewById(R.id.button);
    plus5b.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            plussound.start();
            for (int i = 1; i <= 5; i++) {
                counterValue++;
            }
            counterdown.setText(String.valueOf(counterValue));
        }
    });
}

One MediaPlayer can only play one sound at a time, so you need to create a new MediaPlayer for each sound, so create it inside the onClick method. 一个MediaPlayer一次只能播放一种声音,因此您需要为每种声音创建一个新的MediaPlayer ,因此请在onClick方法中创建它。 Also make sure to get rid of it after the sound is played (using a MediaPlayer.OnCompletionListener ) to avoid having memory issues. 另外,请确保在播放声音后使用MediaPlayer.OnCompletionListener消除声音,以避免出现内存问题。

Button plus5b = (Button)findViewById(R.id.button);
plus5b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        MediaPlayer mediaPlayer = MediaPlayer.create(basic_2.this, R.raw.plus);    
        // Adding an onCompletionListener to ensure the MediaPlayer releases the memory after playing
        plussound.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mediaPlayer.release();
                mediaPlayer = null;
           }
        });
        mediaPlayer.start();

        for (int i = 1; i <= 5; i++) {
            counterValue++;
        }
        counterdown.setText(String.valueOf(counterValue));
    }
});

If you wanted to have the sound overlay you would need the code to be the following: 如果要覆盖声音,则需要以下代码:

Button plus5b = (Button)findViewById(R.id.button);
plus5b.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for (int i = 1; i <= 5; i++) {
            counterValue++;
        }
        counterdown.setText(String.valueOf(counterValue));
        plussound.start();
    }
});

The reason the sound method needs to be inside the for loop and not outside of it is because when it is outside and the button is clicked it only goes off once because the action is not repeated every time the user clicks it. 声音方法需要在for循环内而不是外部的原因是,当它在外部并单击按钮时,它仅关闭一次,因为用户每次单击时都不会重复操作。

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

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