gpt4 book ai didi

android - 一次播放两个媒体播放器

转载 作者:行者123 更新时间:2023-12-03 02:14:20 25 4
gpt4 key购买 nike

我创建了一个应用,在一个布局(仅将其称为布局A)中,我播放媒体播放器,然后当我转到另一个布局(仅将其称为布局B)时,我希望来自布局A的声音继续播放布局B,当我回到布局A时,我还希望媒体播放器仍继续播放之前播放的音乐。

在布局A中,我在onCreate中设置以下代码:

    player = MediaPlayer.create(this, R.raw.sound); 
if(!isMuted())
{
player.setLooping(true);
player.start();
}

...

btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent intent = new Intent(A.this, B.class);
stop=1;
startActivity(intent);
}
});

这段代码:
@Override
protected void onPause()
{
super.onPause();
if (stop!=1)
{
//stop=1 if i go to another layout, for example when i want to go to Layout B
//if the device is automatically locked, i want the media player is paused and it resumed when i unlock the device, so i use stop!=1 to know whether the sound should be paused or not
player.pause();
length = player.getCurrentPosition();
}
}

@Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
//isMuted is method to know whether the sound is muted or not, if it isn't muted, then the sound is resumed
player.seekTo(length);
player.setLooping(true);
player.start();
}
}

在布局B中,我在onCreate中使用了以下代码:
 player = MediaPlayer.create(this, R.raw.sound);
....

这段代码:
protected void onPause()
{
super.onPause();
player.pause();
length = player.getCurrentPosition();
}

@Override
protected void onResume()
{
super.onResume();
if(!isMuted())
{
if(player.isPlaying())
{

}
else
{
player.seekTo(length);
player.setLooping(true);
player.start();
}
}
}

但这是问题所在。
  • 当我转到布局B时,来自布局A的Media Player和来自布局B的Media Player同时播放,因此一次同时播放声音。
  • 当我回到布局A时,布局B中的Media Player停止,并且布局A中的Media Player停止并从头开始播放,它没有继续之前播放的Media Player。
  • 当设备锁定时,尽管我使用了指示是否应该暂停的指示符,但媒体播放器仍在播放。对代码有任何更正吗?
  • 最佳答案

    我建议您使用服务来播放和暂停/停止音乐。不建议使用“ Activity ”以这种方式处理音乐。您可以启动服务,然后在其中播放音乐。与后台 Activity 相比,服务在后台运行,不会被自动销毁。这是一个示例应用程序代码,与您需要的功能类似media player sound continue in all activities

    关于android - 一次播放两个媒体播放器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21265825/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com