【问题标题】:i need to stop sound on image button when back button pressed or home button pressed当按下返回按钮或按下主页按钮时,我需要停止图像按钮上的声音
【发布时间】:2022-10-08 01:46:49
【问题描述】:

在图像中,我正在循环播放一种声音 总代码工作正常,但是当我按下图像上的后退按钮或主页按钮时,播放声音并没有停止 请帮助我我是新手我正在自己制作这个应用程序

这是我的代码:

我的 JAVA 代码:

ImageView imgPlay;
ImageView imgPause;
int sound1 = -1;
SoundPool soundPool;


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


    imgPlay = findViewById(R.id.imgPlay);
    imgPause = findViewById(R.id.imgPause);

    final MediaPlayer sound = MediaPlayer.create(play.this, R.raw.song1);


    this.soundPool = new SoundPool(2, 3, 0);
    this.sound1 = this.soundPool.load(this, R.raw.sound1, 1)

    imgPlay.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sound.start();
            sound.setLooping(true);
        }
    });

    imgPause.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            sound.pause();

        }
    });
    
    ((Button) findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener() {
        public void onClick(View view) {
            play.this.soundPool.autoPause();
            play.this.soundPool.play(play.this.sound1, 1.0f, 1.0f, 0, 0, 1.0f);
        }
    });
   
}

}

【问题讨论】:

    标签: android android-studio media-player imagebutton onbackpressed


    【解决方案1】:

    您需要覆盖活动的 onPause 生命周期并在那里暂停声音。

    @Override
    protected void onPause() {
        super.onPause();
        sound.pause();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多