首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >是否在应用程序中播放背景音乐?

是否在应用程序中播放背景音乐?
EN

Stack Overflow用户
提问于 2015-07-15 13:17:21
回答 5查看 10.6K关注 0票数 16

我希望用户能够打开应用程序,并有音乐开始播放。我希望用户能够转到任何视图控制器,并在音乐不停止的情况下返回到初始视图控制器。我想让它无限循环。

我已经尝试将初始视图控制器的viewDidLoad方法放入其中,让它开始播放。发生的情况是,用户离开初始视图控制器,当他们回来时,音乐再次开始播放,与原始副本重叠。

为了纠正这个问题,我放了一个if语句来检查声音是否已经播放,这样就不会启动另一个副本,而viewDidLoad方法完全忽略if语句并再次播放它。我也尝试过使用viewDid/WillAppear。我尝试将声音放在applicationDidLaunchWithOptions方法中的应用程序委托中,但完全没有声音。

EN

回答 5

Stack Overflow用户

发布于 2015-08-21 15:38:38

我是这样做的。将此代码添加到您希望音乐开始播放的类场景之外的任何位置。你甚至可以创建一个全新的Swift文件,然后在其中添加以下代码(导入AVFoundation)

代码语言:javascript
复制
var backgroundMusicPlayer: AVAudioPlayer!

func playBackgroundMusic(filename: String) {

    //The location of the file and its type
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: "mp3")

    //Returns an error if it can't find the file name
    if (url == nil) {
        println("Could not find the file \(filename)")
    }

    var error: NSError? = nil

    //Assigns the actual music to the music player
    backgroundMusicPlayer = AVAudioPlayer(contentsOfURL: url, error: &error)

    //Error if it failed to create the music player
    if backgroundMusicPlayer == nil {
    println("Could not create audio player: \(error!)")
    return
    }

    //A negative means it loops forever
    backgroundMusicPlayer.numberOfLoops = -1
    backgroundMusicPlayer.prepareToPlay()
    backgroundMusicPlayer.play()
}

完成后,转到didMoveToView函数并使用文件名调用该函数。

代码语言:javascript
复制
playBackgroundMusic("IntroMusic")

我刚刚测试了它,切换场景后它工作得很好。

票数 6
EN

Stack Overflow用户

发布于 2016-01-11 23:09:40

只需添加"numberofLoops = -1“,它将在后台无限播放。

示例(Swift):

代码语言:javascript
复制
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)
    }
}

玩得开心。

票数 3
EN

Stack Overflow用户

发布于 2015-07-16 08:52:32

找到了解决方案。我声明了一个名为signal的视图控制器属性。我说signal:==?-然后在viewDidLoad中,我放了一个if语句,如果signal == nil,只播放背景歌曲。然后,在我的其他视图控制器中,我对其进行了设置,以便当它们分割回mainviewcontroller时,信号属性= false。然后,歌曲将不会再次播放,一切都将正常工作。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31422014

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档