MediaPlayer无法正常工作

时间:2016-12-22 07:33:20

标签: android media-player android-mediaplayer

当用户点击按钮时,我使用MediaPlayer播放咔嗒声。有时声音会很好,但有时候声音太慢。例如,第一次点击很好,但第二次点击太慢了 这是我的代码:

private MediaPlayer mClickSound;

@Override
protected void onCreate(Bundle savedInstanceState) {
    ...
    mClickSound = MediaPlayer.create(this, R.raw.click);
}

@Override
public void onClick(View view) {
    try {
        if (mClickSound.isPlaying()) {
            mClickSound.stop();
            mClickSound.release();
            mClickSound = MediaPlayer.create(this, R.raw.click);
        }
        mClickSound.start();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

2 个答案:

答案 0 :(得分:0)

试试这个:

mClickSound.reset();
AssetFileDescriptor afd = context.getResources().openRawResourceFd(R.raw.click);
if (afd == null) return;
mClickSound.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mClickSound.start();
afd.close();

setDataSource取自此处: https://stackoverflow.com/a/20111291/6159609

重置方法应该更快。

答案 1 :(得分:0)

请尝试以下代码正常工作...

public class MainActivity extends AppCompatActivity implements View.OnClickListener
{
    Button btn;
    MediaPlayer mClickSound;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn = (Button) findViewById(R.id.button);
        mClickSound = MediaPlayer.create(this, R.raw.click);
        btn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        if (mClickSound.isPlaying()) {
            mClickSound.reset();
        }
        else {
            mClickSound = MediaPlayer.create(this, R.raw.click);
            mClickSound.start();
        }
    }
}