我正在创建一个应用程序,接收MIDI音符,并根据收到的音符在应用程序中播放音乐。我正在使用AudioKit的AKMIDIListener协议和函数receivedMIDINoteOn。它能够接收这些事件,并从我的应用程序中播放我想要播放的音符。但是,我也试图在ReceivedMIDINoteOn函数中更改UI组件,但我无法这样做。否则,receivedMIDINoteOn将正确地处理它的事件,用户界面不会因为某种原因而改变以反映这一点。我正在更改的UIViewController也有AKMIDIListener协议,receivedMIDINoteOn函数也在UIViewController中定义。我在下面提供了一个代码片段来帮助识别问题。为什么UI组件不能更新?在下面的代码中,"playButton“在接收到MIDINoteOn函数时不会被更新,尽管我知道该函数是运行的,因为它会播放背景音乐。此外,每当我在代码中的其他函数中使用更改标题时,playButton也相应地更改了它的标题
let midi = AudioKit.midi
class firstPageViewController: UIViewController, AKMIDIListener {
@IBOutlet var MusicButtons: [UIButton]!
@IBOutlet var playButton: UIButton!
@IBOutlet var pauseButton: UIButton!
@IBOutlet var WaveForm: AudioVisualizationView!
@IBOutlet weak var firstButton: UIButton!
@IBOutlet weak var secondButton: UIButton!
@IBOutlet weak var thirdButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
isOnFirstPage = true
isOnSecondPage = false
isOnThirdPage = false
self.secondButton.setTitleColor(UIColor.blue, for: .normal)
self.thirdButton.setTitleColor(UIColor.blue, for: .normal)
midi.openInput()
midi.addListener(self)
self.init_buttons()
self.init_soundwave()
self.init_audio()
}
func receivedMIDINoteOn(noteNumber: MIDINoteNumber, velocity: MIDIVelocity, channel: MIDIChannel) {
let currNum = mapping[Int(noteNumber)]
if currNum == 64 { //Play button
self.playBackground(0)
self.playButton.setTitle("Currently Playing", for: .normal)
}
else if currNum == 67 { //Pause button
self.pauseMusic(0)
self.playButton.setTitle("Play", for: .normal)
}
else if currNum == 68 { //Switch button - first page
self.firstPageSwitch(0)
}
else if currNum == 69 { //Switch button - second page
self.secondPageSwitch(0)
}
else if currNum == 70 { //Switch button - third page
self.thirdPageSwitch(0)
}
else if currNum == 71 {
//
}
else if currNum == 65 {
//
}
else if currNum == 66 {
//
}
else {
if isOnFirstPage! {
self.playMusic(currNum: currNum!, holder: audioPlayer)
self.MusicButtons![currNum!].backgroundColor = UIColor(red: 247/255, green: 183/255, blue: 98/255, alpha: 1.0)
}
if isOnSecondPage!{
self.playMusic(currNum: currNum!, holder: secondAudioPlayer)
self.MusicButtons![currNum!].backgroundColor = UIColor(red: 247/255, green: 183/255, blue: 98/255, alpha: 1.0)
}
}
}
}
发布于 2018-11-10 22:20:20
注释是正确的,您需要将您的UI调用包装在
DispatchQueue.main.async {
// ... code here
}
也许还得在最后加上一个self.playButton.setNeedsDisplay()
。
https://stackoverflow.com/questions/53243444
复制相似问题