当我从视图导航到视图时,如何让音乐持续存在?

时间:2015-04-28 01:31:05

标签: ios iphone swift avaudioplayer audio-player

所以,我已经掌握了在iOS中使用一个视图播放声音/音乐的艺术,但我现在正在尝试为音乐艺术家制作更强大的应用程序。到目前为止,它涉及从“菜单”ViewController到他的Bio,Show Times和“Listening Room”等的segue。到目前为止,我创建了一个“AudioManager”类:

import UIKit
import AVFoundation
import MediaPlayer

class AudioManager: NSObject {

    let defaltSong = ["Hell&BackCaf/01 Black Sheep", "caf"]
    weak var delegate : PlayerDelegate?
    var musicPlayer1 = AVAudioPlayer()
    var trackNumber = 0

    var musicAudioPath = NSBundle.mainBundle().pathForResource("Hell&BackCaf/01 Black Sheep", ofType: "caf")
    var musicAudioPathURL = NSURL()
    var error:NSError? = nil


    var songList = [["Hell&BackCaf/01 Black Sheep", "caf"], ["Hell&BackCaf/02 Hell & Back", "caf"], ["Hell&BackCaf/03 Save Me", "caf"], ["Hell&BackCaf/04 Broken feat. Hillary Dodson", "caf"], ["Hell&BackCaf/05 Do Or Die", "caf"], ["Hell&BackCaf/06 Divided", "caf"]]

    func ButtonPlay(song: NSString, type: NSString) {

        error = nil

        musicAudioPath = NSBundle.mainBundle().pathForResource(song as String, ofType: type as String)

        musicAudioPathURL = NSURL(fileURLWithPath: self.musicAudioPath!)!

        musicPlayer1 = AVAudioPlayer(contentsOfURL: musicAudioPathURL, error: &error)

        musicPlayer1.prepareToPlay()

        musicPlayer1.play()
    }

    func loadFirstSong() {

        error = nil

        musicAudioPath = NSBundle.mainBundle().pathForResource("Hell&BackCaf/01 Black Sheep", ofType: "caf")
        musicAudioPathURL = NSURL(fileURLWithPath: self.musicAudioPath!)!
        musicPlayer1 = AVAudioPlayer(contentsOfURL: musicAudioPathURL, error: &error)
        if error == nil {
            musicPlayer1.prepareToPlay()
        } else {
            println(error)
        }


    }


    func advanceTrack(){

        if trackNumber < songList.count - 1 {

            self.trackNumber++

            ButtonPlay(songList[trackNumber][0], type: songList[trackNumber][1])            
        } else {

            trackNumber = 0

            ButtonPlay(songList[trackNumber][0], type: songList[trackNumber][1])
        }
    }

    func previousTrack(){

        if trackNumber > 0 {

            trackNumber--

            ButtonPlay(songList[trackNumber][0], type: songList[trackNumber][1])

        } else {

            trackNumber = songList.count - 1

            ButtonPlay(songList[trackNumber][0], type: songList[trackNumber][1])
        }

    }

    func audioPlayerDidFinishPlaying(AVAudioPlayer!, successfully: Bool) {
        self.delegate?.soundFinished(self)
        println("song over")
    }



}

然后我在MusicRoomViewController中使用它:

import UIKit
import AVFoundation

class MusicRoomViewController: UIViewController, AVAudioPlayerDelegate {

    let audioManager = AudioManager()

    @IBAction func pressedBackButton(sender: UIButton) {
        audioManager.previousTrack()
    }

    @IBAction func pressedPlayButton(sender: UIButton) {
        audioManager.musicPlayer1.play()
    }

    @IBAction func pressedForwardButton(sender: UIButton) {
        audioManager.advanceTrack()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        audioManager.loadFirstSong()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }

    override func viewWillDisappear(animated: Bool) {

        if self.isMovingFromParentViewController()
        {
            audioManager.musicPlayer1.play()
        }
    }

}

但是现在当我导航到应用程序的任何其他“页面”时,音乐停止了。经过研究,我知道我的这一切都错了,但我似乎无法弄清楚我需要做什么来保持音频播放直到应用程序关闭或用户按下停止(这还不存在,我知道)。有什么想法??

2 个答案:

答案 0 :(得分:1)

您必须将AudioManager类设为单例。发生了什么,一旦您离开您创建它的视图,您正在创建的AudioManager实例将被解除分配。单个对象在首次访问时会被创建,并且会一直存在于内存中,直到应用程序为止#39 ; s生命周期结束或明确解除分配。有关Swift单身人士的更多信息,请查看this page。这是一个有用的学习模式。

对AudioManager进行以下修改(取自上述网站):

private let _AudioManagerSharedInstance = AudioManager()

class AudioManager {
    static let sharedInstance = AudioManager()
}

使用AudioManager.sharedInstance访问AudioManager,例如您可以拨打AudioManager.sharedInstance.previousTrack()

答案 1 :(得分:0)

你可以创建一个单例,或者在AppDelegate类中实例化AudioManager并像这样引用它:

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];

appDelegate.audioManger...