在应用中播放背景音乐?

11 audio avfoundation avaudioplayer ios swift

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

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

为了解决这个问题,我在if语句中检查声音是否已经播放以不启动另一个副本,并且viewDidLoad方法完全忽略if语句并且无论如何都要再次播放它.我也试过用viewDid/WillAppear.我已经尝试将声音放在applicationDidLaunchWithOptions方法中的app委托中,我完全沉默了.

小智 11

使用单例也可以:

import AVFoundation

class MusicHelper {
    static let sharedHelper = MusicHelper()
    var audioPlayer: AVAudioPlayer?

    func playBackgroundMusic() {
        let aSound = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("coolsong", ofType: "mp3")!)
        do {
            audioPlayer = try AVAudioPlayer(contentsOfURL:aSound)
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.play()
        } catch {
            print("Cannot play the file")
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

然后你可以在任何类中使用它(根据Swift 2.1)

MusicHelper.sharedHelper.playBackgroundMusic()
Run Code Online (Sandbox Code Playgroud)


Jos*_*rez 6

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

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()
}
Run Code Online (Sandbox Code Playgroud)

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

playBackgroundMusic("IntroMusic")
Run Code Online (Sandbox Code Playgroud)

我刚刚测试了一下,切换场景后效果很好。


Sha*_*han 5

斯威夫特 4.2 更新

第 1 步。创建一个新类“MusicHelper”

第 2 步。从下面复制和粘贴代码

import AVFoundation

class MusicHelper {
static let sharedHelper = MusicHelper()
var audioPlayer: AVAudioPlayer?

func playBackgroundMusic() {
    let aSound = NSURL(fileURLWithPath: Bundle.main.path(forResource: "MUSICNAME(replece file name)", ofType: "mp3")!)
    do {
        audioPlayer = try AVAudioPlayer(contentsOf:aSound as URL)
        audioPlayer!.numberOfLoops = -1
        audioPlayer!.prepareToPlay()
        audioPlayer!.play()
    }
    catch {
        print("Cannot play the file")
    }
}
Run Code Online (Sandbox Code Playgroud)

第 3 步。将下面的代码复制并粘贴到您的视图控制器

import AVFoundation  //import at the top

var player: AVAudioPlayer?  //declare in code

MusicHelper.sharedHelper.playBackgroundMusic() //paste in viewDidLoad
Run Code Online (Sandbox Code Playgroud)


小智 1

找到了解决方案。我声明了一个名为 signal 的视图控制器属性。我说信号:布尔?- 然后在 viewDidLoad 中我放置了一个 if 语句,仅在 signal == nil 时播放背景歌曲。然后,在我的其他视图控制器中,我将其设置为当它们返回到主视图控制器时,信号属性 = false。然后,该歌曲将不会再次播放并且一切正常。