从swift 2.0中的另一个UIViewController调用一个方法

时间:2015-10-10 09:48:54

标签: ios iphone swift

我有一个播放歌曲的应用程序,我有一个外部类,它有一个playSound函数和所需的所有变量:

class Song: NSObject {

    var audioPlayer: AVAudioPlayer!
    var deviceCurrentTime: NSTimeInterval!

    func playSong() {

        let sound = NSBundle.mainBundle().pathForResource("song", ofType: "mp3")
        let soundData = NSData(contentsOfFile: sound!)
        //  self.audioPlayer = AVAudioPlayer(data: soundData!) throws

        self.audioPlayer = nil
        do {
            self.audioPlayer = try AVAudioPlayer(data: soundData!)
        }
        catch {
            print("Handle \(error) here")
        }

        let delay:NSTimeInterval = 0.0//100ms
        var playtime:NSTimeInterval
        playtime = audioPlayer.deviceCurrentTime + delay

        self.audioPlayer?.playAtTime(playtime)
        self.audioPlayer?.play()


    }

然后在我的mainViewController的ViewDidLoad中,我想播放歌曲,从我的Song对象中访问该方法:

    super.viewDidLoad()

    let vc: NSObject = Song()
    if let myVc = vc as? Song {
        myVc.playSong()
    }

但是没有播放这首歌...如果我将所有变量从Song放到mainViewControler中也使用playSong方法并在viewDidLoad中说playSong(),它可以工作,但我想在外部类中使用它。 / p>

请帮忙吗? :)

1 个答案:

答案 0 :(得分:1)

您可以创建一个全局方法。创建一个空的swift文件并在其中添加此代码:

import Foundation
import AVFoundation


var backgroundMusicPlayer = AVAudioPlayer()

func playBackgroundMusic(filename: String) {
    let url = NSBundle.mainBundle().URLForResource(filename, withExtension: nil)
    guard let newURL = url else {
        print("Could not find file: \(filename)")
        return
    }
    do {
        backgroundMusicPlayer = try AVAudioPlayer(contentsOfURL: newURL)
        backgroundMusicPlayer.numberOfLoops = -1
        backgroundMusicPlayer.prepareToPlay()
        backgroundMusicPlayer.play()
    } catch let error as NSError {
        print(error.description)
    }
}

现在,当你想要播放任何歌曲时,只需按照这种方式调用该方法:

playBackgroundMusic("yourSong.mp3")

如果你想和你的班级一起去,那么你可以这样做:

import Foundation
import AVFoundation

var audioPlayer: AVAudioPlayer!
var deviceCurrentTime: NSTimeInterval!

class Song: NSObject {

    func playSong() {

        let sound = NSBundle.mainBundle().pathForResource("We_Are_One_Ole_Ola_", ofType: "mp3")
        let soundData = NSData(contentsOfFile: sound!)
        //  self.audioPlayer = AVAudioPlayer(data: soundData!) throws

        audioPlayer = nil
        do {
            audioPlayer = try AVAudioPlayer(data: soundData!)
        }
        catch {
            print("Handle \(error) here")
        }

        let delay:NSTimeInterval = 0.0//100ms
        var playtime:NSTimeInterval
        playtime = audioPlayer.deviceCurrentTime + delay

        audioPlayer?.playAtTime(playtime)
        audioPlayer?.play()

    }
}

在其他课程中,你可以这样使用它:

override func viewDidLoad() {
    super.viewDidLoad()

    let temp = Song()
    temp.playSong()
}