应用程序的背景音乐应该有自己的主题吗? [英] Should an App's background music have a thread of it's own?

查看:56
本文介绍了应用程序的背景音乐应该有自己的主题吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个应用程序,每当调用 onCreate() 时都会播放一段音乐,我希望在整个应用程序(即跨活动)中播放这些音乐.到目前为止,我所做的是在 OnCreate() 中创建一个线程,并将其命名为 backgroundMusic,在其中我从原始文件夹中的音乐作品创建了一个 MediaPlayer 对象.考虑到音乐本身只运行一分钟左右,并且平均花费在应用程序上的时间更多,我做了一个循环,只要应用程序正在运行,就会检查音乐是否正在播放,如果没有,则调用 start();

I'm trying to build an app where a piece of Music is played whenever the onCreate() is called, and I want for this music to be played throughout the whole app ie across Activities. what I've done so far is to create a Thread,within the OnCreate(), and I called it backgroundMusic, inside of it I created A MediaPlayer Object from a music piece in my Raw Folder. given that the music itself only runs for a minute or so and the average time spent on the app is more, I made a while Loop that as long as the app is running checks if the music is playing, if not then call start();

backgroundMusic = new Thread(new Runnable() {
    @Override
    public void run() {
        while ( appIsRunning ){

            if( ! music.isPlaying () ){
                music.start();
            }
        }
    }
});backgroundMusic.start();

代码运行得很好,但是我确实注意到一些滞后,尤其是在加载其他一些线程和图像之后.我想问的是,这是播放背景音乐的合适方式吗?有没有更好更有效的方法来做到这一点?另外,如何在应用关闭时让音乐停止?

the code runs just fine, however I did notice some Lag especially later when some other Threads and Images gets loaded.what I want to ask, is this an appropriate way to play background Music? is there a better more efficient way of doing that? also, how do I make the music stop as the app closes?

推荐答案

这是播放背景音乐的合适方式吗?

is this an appropriate way to play background Music?

不,您需要在服务上声明音乐.一项服务:

No, you need to declare music on a service. A service :

  • 将独立于活动生命周期,因此当活动关闭时音乐将继续播放

  • Will be independent of activity LifeCycle hence music will keep playing when Activity is closed

可以在需要时暂停,如来电

can be paused when needed like incoming call

这里可以帮助您入门.快乐编码!

Here is something to get you started. Happy coding!

这篇关于应用程序的背景音乐应该有自己的主题吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆