【问题标题】:Single MediaPlayer with multiple MP3s带有多个 MP3 的单个 MediaPlayer
【发布时间】:2018-03-25 22:20:37
【问题描述】:

我的 Android 应用中有一个 SoundService,它允许我播放单个音轨。这是服务类:

public class UnopenedChestService extends Service {
    MediaPlayer unopenedPlayer;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public void onCreate() {
        unopenedPlayer = MediaPlayer.create(this, R.raw.audiofile);
        unopenedPlayer.setLooping(true);
    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        unopenedPlayer.start();
        return Service.START_NOT_STICKY;
    }

    public void onDestroy() {
        unopenedPlayer.stop();
        stopSelf();
        super.onDestroy();
    }
}

这很好用,我可以分别用startService(new Intent...stopService(new Intent... 启动和停止MP3 文件audiofile

我想添加可以在我的应用程序中播放的第二个声音。我已经进行了一些挖掘,唯一接近解决我的问题的解决方案是创建另一个 SoundService 并播放不同的音频文件。

我这样做了,效果很好。

我的问题是感觉很浪费。我有很多重复的代码,并且不断地停止和启动SoundService 的 2 个变体感觉很hacky。

有没有比上述更好的解决方案,可以让我使用单个 SoundService 在 MP3 文件之间切换?

【问题讨论】:

    标签: java android


    【解决方案1】:

    您可以在启动/调用服务时通过 Intent 传递参数(例如歌曲名称)。在您的 onStartCommand 中,您将获取这些参数(例如歌曲的名称)并播放所选歌曲。这应该可以。

    【讨论】:

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