I'm using XLWINGS to add some functionality to Excel. I want to be able to use a specific audio player with specific codecs to play audio files when the hyperlink in the excel cell is clicked (not when the hyperlink formula is written to its cell).
The xlwings UDF is:
@xw.func(volatile=False)
def play_audio(audiofilepath):
'''
Use the audioplayer defined at the top of the module as a
path to an executable to
open the audiofile. The audioplayer auto-closes when the
reproduction of the audio file is complete as the timeout
parameter is equal to the calculated duration of the file
'''
#Get file length in seconds
with contextlib.closing(wave.open(audiofilepath,'r')) as f:
frames = f.getnframes()
rate = f.getframerate()
length = frames / float(rate)
'''
Use the defined audioplayer to play the file and
close out the app after the files duration
'''
try:
subprocess.run([audioplayer,audiofilepath], timeout = length)
except:
pass
The code XLWINGS uses to write the hyperlink to excel is:
write_cell.value = '=HYPERLINK(play_audio("{}"),"OK")'.format(fullpathandfilename)
I've also tried:
write_cell.add_hyperlink(address = '=play_audio("{}")'.format(fullpathandfilename),text_to_display ="OK",screen_tip=fullpathandfilename)
The excel hyperlink written looks like this:
=HYPERLINK(play_audio("path\to\audio.wav"),"PLAY")
This works but I have an unwanted behaviour:
- Each time xlwings writes this formula to a cell, the play_audio() code referred to by the HYPERLINK formula is executed (meaning the audio is played and bottle necks the writing process). I want excel to evaluate the formula when the user clicks the hyperlink but it seems to be triggered by other events like saving, closing or other events in the workbook.
I reviewed this particular post and reviewed this page of reference but I want to avoid having to code the solution in VBA if at all possible and keep all code coherent in the same py file.
Any ideas?
Thanks!