Basically, I'm trying to detect when the user has copied something to the clipboard and perform an action. In this case, I am trying to play a sound; I have imported the sound file to Xcode. However, It crashes because of the while loop and if I remove the while loop it still crashes because I restart the program in the end. How should I go about doing this because I always end up in a loop and eventually program crashes and can't detect a change in the NSPasteboard's changeCount. Also the sound file does not work, and I can't seem to figure out why. Any help would be awesome!!!! Writing it in Swift only.
Edit 1: I know why it's crashing, I just don't know any other way to do it.
import Cocoa
import AVFoundation
class ViewController: NSViewController {
let pasteboard = NSPasteboard.general
override func viewDidLoad() {
super.viewDidLoad()
let sound = URL(fileURLWithPath: Bundle.main.path(forResource: "sound", ofType: "mp3")!)
var audioPlayer: AVAudioPlayer?
//intializing audio player
do
{
try audioPlayer = AVAudioPlayer(contentsOf: sound)
}catch{
print("fail")
}
let lastChangeCount=pasteboard.changeCount
//keep looping until something is copied.
while(pasteboard.changeCount==lastChangeCount){
}
//something is copied to clipboard so play audio
audioPlayer?.play()
//restart program
self.viewDidLoad()
}
Polling with while
loops is very bad habit and you must not call viewDidLoad
, never.
This version uses a Timer
which fires once per second and checks the pasteboard in the closure.
For playing a simple sound AVFoundation
is overkill
class ViewController: NSViewController {
var lastChangeCount = 0
var timer : Timer?
override func viewDidLoad() {
super.viewDidLoad()
let pasteboard = NSPasteboard.general
lastChangeCount = pasteboard.changeCount
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) { [unowned self] timer in
if pasteboard.changeCount != self.lastChangeCount {
NSSound(named: NSSound.Name("sound"))?.play()
self.lastChangeCount = pasteboard.changeCount
}
}
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments