如何停止在android中循环播放声音?

时间:2019-06-23 02:52:00

标签: java android

我需要播放1次声音,但他正在无限循环。

我不明白为什么会这样。

如果我使用内置声音“ mediaPlayer = MediaPlayer.create(MainActivity.this, R.raw.test);”-声音没有循环。

如果我使用外部声音“ mediaPlayer = MediaPlayer.create(MainActivity.this,Uri.parse(audio.getPath()));” -声音在循环。

这是我的代码

mediaPlayer = MediaPlayer.create(MainActivity.this, Uri.parse(audio.getaPath()));
mediaPlayer.setLooping(false);

mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
    public void onPrepared(MediaPlayer mp)
    {

        mp.start();
    }
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
{
    public void onCompletion(MediaPlayer mp)
    {
        finish();
    }
});

有人可以帮助我吗?谢谢

3 个答案:

答案 0 :(得分:0)

您应该使用mp.pause()而不是finish()

       mediaPlayer = MediaPlayer.create(MainActivity.this, 
          Uri.parse(audio.getaPath()));
         mediaPlayer.setLooping(false);

         mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
           {
     public void onPrepared(MediaPlayer mp)
        {

    mp.start();
     }
   });
       mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener()
   {
        public void onCompletion(MediaPlayer mp)
     {
            mp.pause();
               }
                });

答案 1 :(得分:-1)

在按钮中:

    Intent intent_upload = new Intent();
    intent_upload.setType("audio/*");
    intent_upload.setAction(Intent.ACTION_GET_CONTENT);
    startActivityForResult(intent_upload, 222);

结果:

 @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch (requestCode) {

        case 222:
            if (requestCode == 222) {

                if (resultCode == RESULT_OK) {

                    //the selected audio.
                    Uri uri = data.getData();

                    MediaPlayer mediaPlayer = MediaPlayer.create(this, uri);
                    mediaPlayer.setLooping(false);

                    mediaPlayer.setOnPreparedListener(mp -> mp.start());
                    mediaPlayer.setOnCompletionListener(mp -> finish());

                }
            }
            break;
        default:
            super.onActivityResult(requestCode, resultCode, data);
            break;
    }
}

我尝试过,并且效果很好,也许您错过了活动中的某些内容?

答案 2 :(得分:-1)

尝试此代码

 private MediaPlayer mMediaPlayer;
public void stop() {
    if (mMediaPlayer != null) {
        mMediaPlayer.release();
        mMediaPlayer = null;
    }
}
public void play(Context context, String name) {
    stop();

    //mMediaPlayer = MediaPlayer.create(c, rid);
    mMediaPlayer = MediaPlayer.create(context, Uri.parse("android.resource://"+ context.getPackageName()+"/your_file/"+name+".mp3"));
    mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
        @Override
        public void onCompletion(MediaPlayer mediaPlayer) {
            stop();
        }
    });