Multimedia: introducing the webbrowser module

vegaseat 4 Tallied Votes 1K Views Share

Probably the simplest way to get into multimedia with Python is the webbrowser module. This works with both Windows and Unix systems, and selects the default browser you have installed. But that is not all: if you give it the name of a multimedia file it will select the default viewer or player, at least in Windows systems.

An example sound file might look like this:

import webbrowser
# opens .wav file with default wave sound player
webbrowser.open("Train.wav")

Whereas to display a bitmap graphics file you would have something like:

import webbrowser
# opens a .bmp file with default picture viewer
webbrowser.open("Train.bmp")

But the real power of the webbrowser module can be seen when you realize that it will load the browser with HTML code that can quickly be created from within a Python script. What this gives you is the ability to combine a picture with some sound, as highlighted in the following example:

import webbrowser
# html code to show a picture with sound effect
# you can replace files train.bmp and train.wav in the code
# with an image (.bmp, .gif, .jpg) and sound file (.wav, .au) you have
# you may need to change width and height to fit your own picture
# make sure the image and sound files are in the working folder
str1 = """
<html>
<head>
<title>Bring up an image with sound</title>
</head>
<body>

<img src = "train.bmp" width=320 height=210 border=5>

<bgsound src = "train.wav" loop=2>

</body>
</html>
"""

# write the html file to the working folder
fout = open("SoundImage.htm", "w")
fout.write(str1)
fout.close()

# now open your web browser to run the file
webbrowser.open("SoundImage.htm")

Yet the flexibility of the webbrowser module goes even further, because simple HTML code can be used to show several pictures at once. How about having two animated gif graphics next to each other to spell HI? Even if your default viewer didn't work with animated gifs, this will work because browsers just love animated gifs. Here is the example code:

import webbrowser
# html code to dislay two animated gifs next to each other
str1 = """
<html>
<head>
<title>Animated HI</title>
</head>
<body>

<img src="Ag_H.gif" width=170 height=170 border=0>
<img src="Ag_I.gif" width=170 height=170 border=0>

</body>
</html>"""

# write the html file to the working folder
fout = open("Animated_HI.htm", "w")
fout.write(str1)
fout.close()

# now open your web browser to run the file
webbrowser.open("Animated_HI.htm")

Want to do even more? No problem, how about showing three pictures with overlap:

import webbrowser

# html code to overlap three pictures
# if you supply your own pictures, you may have to change
# widths, heights and absolute positions
str1 = """
<html>
<head>
<title>Overlaping Images</title>
</head>
<body bgcolor="#66CC33">
<!-- you may need to supply your own image files -->
<!-- and adjust their widths and heights accordingly -->
<div style="position:absolute; left:250; top:420; width:360; height:245">
    <img id = "image1" width = 360 height = 245  src = "Benz88L.jpg">
</div>

<div style="position:absolute; left:150; top:220; width:360; height:245">
    <img id = "image2" width = 360 height = 245  src = "Benz84L.jpg">
</div>

<div style="position:absolute; left:50; top:20; width:360; height:245">
    <img id = "image3" width = 360 height = 245  src = "Benz83L.jpg">
</div>

</body>
</html>"""

# write the html file to the working folder
fout = open("ImageOverlap.htm", "w")
fout.write(str1)
fout.close()

# now open your web browser to run the file
webbrowser.open("ImageOverlap.htm")

Amazingly, webbrowser is not finished yet, because browsers also like MIDI files that play sound effects and instrumental background music. The small size of the .mid file means that it can be transmitted quickly on the Internet. You could use webbrowser.open("MyDrums.mid") and it would find a default player, but you can also embed the file within HTML code like this:

import webbrowser

# html code to embed a midi music file for background music
str1 = """
<html>
<head>
<title>Embedded MIDI Player</title>
</head>
<body text="#FF66CC" onLoad="resizeTo(460,320)">
<h4>The midi file will auto start!</h4>
<!--  you can put your own midi file here -->
<embed src = "Drum1.mid"  width="400" height="20"
   hidden=false autostart=true loop=1>
</body>
</html>"""

# write the html file to the working folder
fout = open("EmbeddedMidi.htm", "w")
fout.write(str1)
fout.close()

# now open your web browser to run the file
webbrowser.open("EmbeddedMidi.htm")

You can even play movies in the MPG, MOV, AVI, SWF formats just by modifying the above HTML code string very slightly as follows:

str1 = """
<html>
<head>
<title>Embedded MPG Player</title>
</head>
<body>
<!--  put your own .mpg movie file here -->
<!--  adjust width and height to your needs  -->
<embed src = "Whateveryouhave.mpg"  width="400" height="350"
   hidden=false autostart=true loop=1>
</body>
</html>
"""

And finally, for those amongst you that don't like cluttering your drives with temporary files, there is even the option of creating a temporary http server specifically to handle the webbrowser request, using the following code:

# display html in the default web browser without creating a temp file
# does not write needed .bmp and .wav files to the temporary http server,
# so you have to give full pathnames for these files!

import BaseHTTPServer as bhs
import webbrowser

def load_default_browser(html):
    class RequestHandler(bhs.BaseHTTPRequestHandler):
        def do_GET(self):
            bufferSize = 1024*1024
            for i in xrange(0, len(html), bufferSize):
                self.wfile.write(html[i:i+bufferSize])

    # create a temporary http server to handle one request
    server = bhs.HTTPServer(('127.0.0.1', 0), RequestHandler)
    # calls URL to retrieve html from the temporary http server
    webbrowser.open('http://127.0.0.1:%s' % server.server_port)
    server.handle_request()

html = """<html>
<head>
<title>image with sound</title>
</head>
<body>
<!--  give full path for your picture and sound files  -->
<IMG SRC="D:/Python24/Atest/train.bmp" WIDTH=320 HEIGHT=210 BORDER=5>
<bgsound src="D:/Python24/Atest/train.wav" loop=2>
</body>
</html>
"""

load_default_browser(html)

All the multimedia files used in this tutorial can be found in the attached Multimedia.zip file

Ene Uran commented: sweet +13
vegaseat 1,735 DaniWeb's Hypocrite Team Colleague

For some odd reason it seems that the zip file containing the multimedia test files got lost. Well here it is ...

wwwalker 49 Newbie Poster

That webbrowser module in Python works fine on Debian Linux! I just opened a basic HTML page in lynx. So it even works on Linux with no GUI!

1337455 10534 0 Light Poster

It uses firefox to play mp3's. Odd.
But overall 10/10.

Dan08 8 Junior Poster

Im really impressed, it works perfectly on windows vista, nice work.
5 Stars.

e-papa 13 Posting Pro in Training

I think I'll learn a lot from this thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.