2

I'm trying to write a simple python script to stop the music being played by a Mac. I found some code that emulates the media buttons from the accepted answer here: emulate media key press on Mac.

Triggering the play/pause button works perfectly, but I only want to do so if there is music currently playing. Otherwise it turns on the music (the opposite of what I'm trying to do. Is there any way to get this information from the system?

I need to check if music was actually playing beforehand so I can know whether to resume it later.

Community
  • 1
  • 1
Matt Cooper
  • 2,042
  • 27
  • 43

1 Answers1

2

If your use case is macOS specific, you can call AppleScript via Python:

import subprocess
subprocess.call(['osascript', '-e', 'tell application "iTunes" to pause'])
Daniel Corin
  • 1,987
  • 2
  • 15
  • 27
  • Thanks! This works well. For spotify I had to tweak it to `subprocess.call(['osascript', '-e', 'tell application "Spotify" to pause'])`. However, this doesn't solve my whole problem. I need to check if music was actually playing beforehand so I can know whether to resume it later. (Sorry I wasn't more specific in the original post – edited now.) – Matt Cooper Sep 23 '15 at 03:25
  • 1
    [This post](http://stackoverflow.com/questions/27604207/applescript-check-if-computer-is-playing-any-sound) might help. You can use `pmset -g` to see if `coreaudiod` is running. – Daniel Corin Sep 23 '15 at 04:40
  • Unfortunately that gives the same response whether Spotify is playing or paused. – Matt Cooper Sep 23 '15 at 16:29
  • 1
    Looks like Spotify has AppleScript bindings you can use to check the player status. You might be able to modify the code from [this post](http://stackoverflow.com/questions/13435412/spotifys-player-state-is-available-in-the-editor-but-in-a-packaged-app-it-g) to get what you are looking for. – Daniel Corin Sep 23 '15 at 17:15
  • Perfect, thanks! Actually ended up just coding the whole thing in AppleScript. – Matt Cooper Sep 24 '15 at 00:53