Android背景音乐服务

发布于 2024-12-17 08:02:33 字数 130 浏览 3 评论 0 原文

我正在 Android 中开发一个娱乐应用程序。我想播放背景音乐,并且我想为此使用服务。应用程序有 3 个活动,所有活动都必须播放音乐。此外,当活动暂停时,音乐必须暂停并在被破坏时停止。谁能告诉我该怎么做?有链接或例子吗?

谢谢。

I am developing an entertainment app in android. I want to play background music, and I want to use service for that. App have 3 activities and music must be played across all activities. Also, when activity is paused, music must PAUSE and stopped when destroyed. Can anyone tell me how to do this ? any links or examples ?

Thank you.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

栖迟 2024-12-24 08:02:33

无需服务即可实现

https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

如果您真的想使用媒体播放器通过服务实现这一点

Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

在清单中调用此服务
确保 .BackgroundSoundService 字符串末尾没有空格

<service android:enabled="true" android:name=".BackgroundSoundService" />

Do it without service

https://web.archive.org/web/20181116173307/http://www.rbgrn.net/content/307-light-racer-20-days-61-64-completion

If you are so serious about doing it with services using mediaplayer

Intent svc=new Intent(this, BackgroundSoundService.class);
startService(svc);

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;
    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        player = MediaPlayer.create(this, R.raw.idil);
        player.setLooping(true); // Set looping
        player.setVolume(100,100);

    }
    public int onStartCommand(Intent intent, int flags, int startId) {
        player.start();
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }
    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }
    public void onPause() {

    }
    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

Please call this service in Manifest
Make sure there is no space at the end of the .BackgroundSoundService string

<service android:enabled="true" android:name=".BackgroundSoundService" />
黎夕旧梦 2024-12-24 08:02:33

对于这里的聚会来说太晚了,但我仍然会添加 0.02 美元,Google 发布了一个名为通用音乐播放器的免费示例,您可以使用它来学习在它使用的所有 Android 平台(汽车、手表、移动设备、电视...)上播放音乐在后台播放音乐的服务,请检查一下,非常有帮助。这是该项目的链接
https://github.com/googlesamples/android-UniversalMusicPlayer

way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer

雨的味道风的声音 2024-12-24 08:02:33

当使用 ServiceMediaPlayer 类时,@Synxmax 的答案是正确的,但是您还需要在清单中声明 Service 才能正常工作,像这样:

<service
    android:enabled="true"
    android:name="com.package.name.BackgroundSoundService" />

@Synxmax's answer is correct when using a Service and the MediaPlayer class, however you also need to declare the Service in the Manifest for this to work, like so:

<service
    android:enabled="true"
    android:name="com.package.name.BackgroundSoundService" />
将军与妓 2024-12-24 08:02:33

我运行它时遇到问题,我做了一些更改以使用 mp3 源运行它。这是 BackfrounSoundService.java 文件。考虑一下我的 mp3 文件位于手机的 SD 卡中。

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("service", "onCreate");
        player = new MediaPlayer();
        try {
            player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.setLooping(true); // Set looping
        player.setVolume(100, 100);

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service", "onStartCommand");
        try {
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }

    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }

    public void onPause() {

    }

    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}

i had problem to run it and i make some changes to run it with mp3 source. here is BackfrounSoundService.java file. consider that my mp3 file is in my sdcard in my phone .

public class BackgroundSoundService extends Service {
    private static final String TAG = null;
    MediaPlayer player;

    public IBinder onBind(Intent arg0) {

        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("service", "onCreate");
        player = new MediaPlayer();
        try {
            player.setDataSource(Environment.getExternalStorageDirectory().getAbsolutePath() + "/your file.mp3");
        } catch (IOException e) {
            e.printStackTrace();
        }
        player.setLooping(true); // Set looping
        player.setVolume(100, 100);

    }

    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("service", "onStartCommand");
        try {
            player.prepare();
            player.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 1;
    }

    public void onStart(Intent intent, int startId) {
        // TO DO
    }

    public IBinder onUnBind(Intent arg0) {
        // TO DO Auto-generated method
        return null;
    }

    public void onStop() {

    }

    public void onPause() {

    }

    @Override
    public void onDestroy() {
        player.stop();
        player.release();
    }

    @Override
    public void onLowMemory() {

    }
}
夜无邪 2024-12-24 08:02:33

HelloAndroid 有一个关于这个主题的优秀教程。主题。事实上,这是我在谷歌上得到的第一个点击。在此处询问之前,您应该尝试使用谷歌搜索,因为这是一个很好的做法。

Theres an excellent tutorial on this subject at HelloAndroid regarding this very subject. Infact it was the first hit i got on google. You should try googling before asking here, as it is good practice.

江城子 2024-12-24 08:02:33

使用 START_STICKY 标志创建前台服务。

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
                   handlePauseRequest();
               }
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               }
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);
           }
       }
   }

   return START_STICKY;
}

然后可以从任何活动调用它来播放一些音乐

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)

您可以使用 bindService 并通过相应的 Activity 生命周期方法使 Service 暂停/停止。

这是一个关于在 Android 上在后台播放音乐< /a>

Create a foreground service with the START_STICKY flag.

@Override
public int onStartCommand(Intent startIntent, int flags, int startId) {
   if (startIntent != null) {
       String action = startIntent.getAction();
       String command = startIntent.getStringExtra(CMD_NAME);
       if (ACTION_CMD.equals(action)) {
           if (CMD_PAUSE.equals(command)) {
               if (mPlayback != null && mPlayback.isPlaying()) {
                   handlePauseRequest();
               }
           } else if (CMD_PLAY.equals(command)) {
               ArrayList<Track> queue = new ArrayList<>();
               for (Parcelable input : startIntent.getParcelableArrayListExtra(ARG_QUEUE)) {
                   queue.add((Track) Parcels.unwrap(input));
               }
               int index = startIntent.getIntExtra(ARG_INDEX, 0);
               playWithQueue(queue, index);
           }
       }
   }

   return START_STICKY;
}

This can then be called from any activity to play some music

Intent intent = new Intent(MusicService.ACTION_CMD, fileUrlToPlay, activity, MusicService::class.java)
intent.putParcelableArrayListExtra(MusicService.ARG_QUEUE, tracks)
intent.putExtra(MusicService.ARG_INDEX, position)
intent.putExtra(MusicService.CMD_NAME, MusicService.CMD_PLAY)
activity.startService(intent)

You can bind to the service using bindService and to make the Service pause/stop from the corresponding activity lifecycle methods.

Here's a good tutorial about Playing music in the background on Android

怎樣才叫好 2024-12-24 08:02:33

我找到了两个很棒的资源可以分享,如果其他人通过谷歌遇到这个线程,这可能会对他们有帮助(2018)。
其中一个是这个视频教程,您将在其中看到服务的实际工作原理,这对于初学者来说很有用。

链接:- https://www.youtube.com/watch?v=p2ffzsCqrs8

另一个是这个网站,它将真正帮助您使用背景音频播放器。

链接:- https://www.dev2qa。 com/android-play-audio-file-in-background-service-example/

祝你好运:)

I have found two great resources to share, if anyone else come across this thread via Google, this may help them ( 2018 ).
One is this video tutorial in which you'll see practically how service works, this is good for starters.

Link :- https://www.youtube.com/watch?v=p2ffzsCqrs8

Other is this website which will really help you with background audio player.

Link :- https://www.dev2qa.com/android-play-audio-file-in-background-service-example/

Good Luck :)

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文