ios - 快速从另一个 ViewController 调用函数

标签 ios swift avplayer

我已经查看了 Stackoverflow,但无法得到答案。我想创建停止在另一个 ViewController 中播放声音的功能。但是当我点击停止按钮时,它崩溃了并显示“EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)”。这是我的代码。

第一个 View Controller

import UIKit
import AVFoundation

class FirstVC: UIViewController {

   var metronome: AVAudioPlayer!
   override func viewDidLoad() {
       super.viewDidLoad()
   do {
        let resourcePath1 = Bundle.main.path(forResource: "music", ofType: "mp3")
        let url = NSURL(fileURLWithPath: resourcePath1!)
        try metronome = AVAudioPlayer(contentsOf: url as URL)

        metronome.prepareToPlay()
        metronome.play()
    } catch let err as NSError {
        print(err.debugDescription)
    }
}

另一个Viewcontroller是

import UIKit
class SecondVC: UIViewController {
   var metronomePlay = FirstVC()

@IBAction func stopBtnPressed(_ sender: Any) {
   metronomePlay.metronome.stop() //"EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)"
   }
}

最佳答案

从今天的 swift 4.1 开始,这段代码对我有用:

将其放入发送 Controller 中:

NotificationCenter.default.post(name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)

将其放入接收 Controller viewDidLoad() 或 viewWillAppear() 中:

NotificationCenter.default.addObserver(self, selector: #selector(disconnectPaxiSocket(_:)), name: Notification.Name(rawValue: "disconnectPaxiSockets"), object: nil)

然后是接收 Controller 类中的以下函数:

@objc func disconnectPaxiSocket(_ notification: Notification) {
    ridesTimer.invalidate()
    shared.disconnectSockets(socket: self.socket)
}

关于ios - 快速从另一个 ViewController 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42135402/

相关文章:

ios - 如何在ios6中卸载 View ?

ios - swift 4 可编码 : Converting JSON return String to Int/Date/Float

ios - 在异步加载中重新加载数据

ios - AVPlayer:在 Swift 中播放 “on the fly” 转码音频文件

swift - 使用 AVFoundation 和 Swift 访问多个音频硬件输出/ channel

ios - 如何从 AVPlayer 中提取隐藏式字幕/字幕

ios - 如何保持按钮被选中?

java - Swift 将字节数组转换为整数

ios - 统一firebase ios错误

ios - AVPlayerItemVideoOutput copyPixelBufferForItemTime针对特定视频在iOS上给出了不正确的CVPixelBufferRef