AppleScript: Switch to tab that's playing audio

Hi guys, I currently have a "Now Playing Widget" and I would like to be able to long press it and if the audio is playing through a browser, I would like it to launch the browser and have it switch to the tab where the audio/video is playing.
I don't see an existing Action in the Long Press Action dropdown menu so I think I'll have to use AppleScript to do what I want. Can someone please shed some light on how to program this in AppleScript? Thanks in advance!

Hi @cyrus0708, I gave it a shot in Javascript for Automation instead of Applescript. I hope you find this helpful!

// A script to open the browser tab which is playing audio

app = Application.currentApplication()
app.includeStandardAdditions = true

var BetterTouchTool = Application('BetterTouchTool');

// define your shared secret 
var secret = '*****';

var browserNames = {'com.google.Chrome': 'Google Chrome', 'com.apple.Safari': 'Safari'}

var BTTCurrentlyPlayingApp = BetterTouchTool.get_string_variable("BTTCurrentlyPlayingApp", {'shared_secret': secret});

if (BTTCurrentlyPlayingApp) {
	var BTTNowPlayingInfoTitle = BetterTouchTool.get_string_variable("BTTNowPlayingInfoTitle", {'shared_secret': secret});

var browserName = browserNames[BTTCurrentlyPlayingApp];

if (browserName == 'Google Chrome') {
	var browser = Application('Google Chrome');
	
} else if (browserName == 'Safari') {
	var browser = Application('Safari');
} else {
	"no browser"
}


var windows = browser.windows;
		
var notFound = true;	
		
for (i = 0 ; i < windows.length & notFound ; i++) {
		
	var window = windows[i];
	var tabs = window.tabs()

	for (tabIndex = 0 ; tabIndex < tabs.length & notFound; tabIndex++) {
		var tab = tabs[tabIndex];
		
		if (browserName == 'Google Chrome') {
			var tabTitleOrName = tab.title();
		} else if (browserName == 'Safari') {
			var tabTitleOrName = tab.name();
		};	
		
		if (tabTitleOrName.includes(BTTNowPlayingInfoTitle)) {
			
			if (browserName == 'Google Chrome') {
				browser.activate();
				app.doShellScript(`/usr/local/bin/chrome-cli activate -t ${tab.id()}`);
				window.index = 1;
			} else if (browserName == 'Safari') {
				browser.activate();
				window.currentTab = tab;
				window.index = 1;
			};	
			console.log('found');
			notFound = false;
			break
		};
			
	};
		
}
} else {
	'nothing playing'
}

Notes:

  • This works for Chrome and Safari. Haven't figured out Firefox yet (in my research for trying to implement it in FireFox, I did come across this post from @Andreas_Hegenberg from 10 years ago haha)
  • For Chrome, you will need to install chrome-cli. Simply enter brew install chrome-cli into your terminal.
  • Don't forget to enter your shared secret
  • If the audio is playing from inside an iframe then it won't work.