播放背景音乐的应用程序? [英] Play background music in app?

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

问题描述

我希望用户能够打开应用程序,并有音乐开始播放。我希望用户能够去任何视图控制器,并返回到最初一个没有音乐停止。我希望它无限循环。

I want the user to be able to open the app and have music start playing. I want the user to be able to go any view controller and return back to the initial one without the music stopping. I want it to loop indefinitely.

我试图把在初始视图控制器的 viewDidLoad中方法,它开始播放。什么情况是,在用户离开初始视图控制器,当他们回来时,音乐又开始播放时,正本重叠。

I have tried to put in the viewDidLoad method of the initial view controller for it to start playing. What happens is, the user leaves the initial view controller and when they come back, the music starts playing again, overlapping the original copy.

要解决这个问题,我把一个if语句检查,如果声音已经打不启动另一个副本和viewDidLoad方法完全忽略if语句并播放一遍反正。我使用 viewDid / WillAppear 也试过。我试图把声音在 applicationDidLaunchWithOptions 方法的应用程序委托,我得到了完全的沉默。

To remedy this, I put an if statement checking if the sound is already to playing to not launch another copy and the viewDidLoad method completely ignores the if statement and plays it again anyways. I also tried using viewDid/WillAppear. I have tried putting the sound in the app delegate in the applicationDidLaunchWithOptions method and I got complete silence.

推荐答案

只需添加numberofLoops = -1的剧本其在infinitly背景。

Just add "numberofLoops = -1" an its plays infinitly in the background.

示例(SWIFT):

func playBackgroundMusic() {
    do {
        if let bundle = NSBundle.mainBundle().pathForResource("someMP3file", ofType: "mp3") {
            let alertSound = NSURL(fileURLWithPath: bundle)
            try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback)
            try AVAudioSession.sharedInstance().setActive(true)
            try audioPlayer = AVAudioPlayer(contentsOfURL: alertSound)
            audioPlayer.numberOfLoops = -1
            audioPlayer.prepareToPlay()
            audioPlayer.play()

        }
    } catch {
        print(error)
    }
}

玩得开心。

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

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