jimztercrack jimztercrack - 7 months ago
250 0

Hello! I want to be able to open the app and have music start playing go any view controller and return back to the initial app without the music stopping. I want it to loop indefinitely here is the code:

Swift

Play background music with swift?

Embed
import UIKit
import AVKit
import AVFoundation


class ViewController: UIViewController, AVPlayerViewControllerDelegate {


    // url for playing video
    var videoUrl: NSURL!





    // action - play local video
    @IBAction func playLocalVideo(sender: UIButton) {

        // create video url from local resource (i.e video stored within project folder)
        self.videoUrl = NSURL(string: "http://file.mp3")

        // perform segue
        self.performSegueWithIdentifier("seguePlayVideo", sender: self)
    }



    // action - play remote video
    @IBAction func playRemoteVideo(sender: UIButton) {

        // create video url form remote location (i.e. video stored at domain etc.)
        self.videoUrl = NSURL(string: "http://playlist.m3u8")

        // perform segue
        self.performSegueWithIdentifier("seguePlayVideo", sender: self)
    }




    // MARK: - View functions

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }




    // MARK: - Navigation function

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {

        if segue.identifier == "seguePlayVideo" {

            // get destination view controller
            let destVc = segue.destinationViewController as! AVPlayerViewController

            // set player
            destVc.player = AVPlayer(URL: self.videoUrl)
        }

    }


}
Comments