ios - 如何让音乐在所有 View 中继续播放

标签 ios swift

我将歌曲放入表格中,当我在详细信息页面中播放歌曲时,当我返回歌曲停止时,我希望在所有 View 中继续播放

View Controller

if let audio=NSBundle.mainBundle().pathForResource( navigationItem.title , ofType: "mp3") {
    let url=NSURL (fileURLWithPath: audio)

    do {
        player = try AVAudioPlayer (contentsOfURL: url)
    }

    catch{"erorr"}       

    player.play()            
} else {
    print("erorr")
}

表格 View Controller

func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
    self.performSegueWithIdentifier("indeaa", sender: tableView)
}

override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
    if segue.identifier == "indeaa" {
        let vc = segue.destinationViewController as UIViewController
        let indexpath:NSIndexPath = tableaa.indexPathForSelectedRow!
        vc.title = arr[indexpath.row]
    }
}

最佳答案

播放器可能随 View 一起释放。您需要让您的播放器可以访问所有详细 View 并引用该单个对象。如果您正在寻找一个简单的解决方案,只需创建一个他们都可以引用的单例:

class AudioPlayer{

  static let sharedInstance = new AudioPlayer();

  var player : AVAudioPlayer

  func playAudio(url : NSURL){

    //see if player is playing, stop and release, setup new player

  }

}

然后从您的详细信息 View 调用

AudioPlayer.sharedInstance.playAudio(url)

Note this isn't tested - but just shows the basic idea.

关于ios - 如何让音乐在所有 View 中继续播放,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34775518/

相关文章:

iphone - QuickDialog 的多行内联条目元素

ios - UITableViewCell 中 UIVisualEffectView 的性能问题

iphone - iPhone 上的视网膜显示屏图像

ios - 我应该使用 KVO 还是 NSNotificationCenter?

ios - 设置 MPNowPlayingInfoCenter 与其他背景音频播放

ios - CollectionView 以 UIScrollView 作为单元格

swift - 我希望标签的物理存在消失-swift

ios - 导航 Controller 在多个 Storyboard 中不起作用

ios - 在不同的碰撞类别上使用单独的函数

ios - 计算 Apple Watch 按下按钮时的百分比