Play background music in app?

南笙酒味 提交于 2019-11-30 18:13:21

Using a singleton works as well:

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")
        }
    }
}

Then you can use it from any class (as per Swift 2.1)

MusicHelper.sharedHelper.playBackgroundMusic()

Here's how I did mine. Add this code anywhere OUTSIDE the class scene where you want the music to start playing. You can even make a whole new Swift file and just add this code in there (import 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()
}

After you have that, go to the didMoveToView function and call the function with the name of the file.

playBackgroundMusic("IntroMusic")

I just tested it and it works perfect after switching scenes.

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

Example (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)
    }
}

Have fun.

Found a solution. I declared a view controller property called signal. I said signal: Bool? - Then in viewDidLoad I put an if statement to only play the background song if signal == nil. Then, in my other view controllers I set it so that when they segue back to the mainviewcontroller, the signal property = false. Then, the song won't play again and everything works correctly.

Swift 4.2 Update

Step 1. Make a new class "MusicHelper"

Step 2. Copy and paste code from below

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")
    }
}

Step 3. Copy and paste code from below to your view controller

import AVFoundation  //import at the top

var player: AVAudioPlayer?  //declare in code

MusicHelper.sharedHelper.playBackgroundMusic() //paste in viewDidLoad
Ruhtra Tam

for swift 4:

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

solved the problem ALHAMDULELLAH only change in Xcode setting

go to setting page>>Capabilities>>Background>>modes>>Allow audio file

I think you should try in you AppDelegate.swift file. In the method application(.....didFinishLaunchingWithOptions.....){} define your AVAudioPlayer() and .play()

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!