Showing posts with label multimedia. Show all posts
Showing posts with label multimedia. Show all posts

Thursday, October 22, 2015

Play a list of WAV files with PyAudio

By Vasudev Ram




While looking at various Python libraries, I remembered PyAudio, which I had blogged about here earlier:

PyAudio and PortAudio - like ODBC for sound

This time I thought of using it to play a list of WAV files. So I wrote a small Python program for that, adapting one of the PyAudio examples. Here it is, in the file pyaudio_play_wav.py:
'''
Module to play WAV files using PyAudio.
Author: Vasudev Ram - http://jugad2.blogspot.com
Adapted from the example at:
https://people.csail.mit.edu/hubert/pyaudio/#docs
PyAudio Example: Play a wave file.
'''

import pyaudio
import wave
import sys
import os.path
import time

CHUNK_SIZE = 1024

def play_wav(wav_filename, chunk_size=CHUNK_SIZE):
    '''
    Play (on the attached system sound device) the WAV file
    named wav_filename.
    '''

    try:
        print 'Trying to play file ' + wav_filename
        wf = wave.open(wav_filename, 'rb')
    except IOError as ioe:
        sys.stderr.write('IOError on file ' + wav_filename + '\n' + \
        str(ioe) + '. Skipping.\n')
        return
    except EOFError as eofe:
        sys.stderr.write('EOFError on file ' + wav_filename + '\n' + \
        str(eofe) + '. Skipping.\n')
        return

    # Instantiate PyAudio.
    p = pyaudio.PyAudio()

    # Open stream.
    stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
        channels=wf.getnchannels(),
        rate=wf.getframerate(),
                    output=True)

    data = wf.readframes(chunk_size)
    while len(data) > 0:
        stream.write(data)
        data = wf.readframes(chunk_size)

    # Stop stream.
    stream.stop_stream()
    stream.close()

    # Close PyAudio.
    p.terminate()

def usage():
    prog_name = os.path.basename(sys.argv[0])
    print "Usage: {} filename.wav".format(prog_name)
    print "or: {} -f wav_file_list.txt".format(prog_name)

def main():
    lsa = len(sys.argv)
    if lsa < 2:
        usage()
        sys.exit(1)
    elif lsa == 2:
        play_wav(sys.argv[1])
    else:
        if sys.argv[1] != '-f':
            usage()
            sys.exit(1)
        with open(sys.argv[2]) as wav_list_fil:
            for wav_filename in wav_list_fil:
                # Remove trailing newline.
                if wav_filename[-1] == '\n':
                    wav_filename = wav_filename[:-1]
                play_wav(wav_filename)
                time.sleep(3)

if __name__ == '__main__':
    main()
Then I ran it as follows:

$ python pyaudio_play_wav.py chimes.wav

$ python pyaudio_play_wav.py chord.wav

$ python pyaudio_play_wav.py -f wav_file_list.txt

where wav_file_list.txt contained these two lines:

chimes.wav
chord.wav
Worked okay and played the specified WAV files. I also ran it a few times with test cases that should trigger errors - the error cases that the current code handles. This worked okay too. You can use one or more WAV files to try out the program. Other than modules in the Python stdlib, the only dependency is PyAudio, which you can install with pip. - Enjoy.

- Vasudev Ram - Online Python training and programming

Signup to hear about new products and services I create.

Posts about Python  Posts about xtopdf

My ActiveState recipes

Thursday, June 26, 2014

pafy - Python API for YouTube

By Vasudev Ram


PAFY (Python API For YouTube) is a Python library that does what the name says on the tin - it allows you to access YouTube videos programmatically, get information about them, download them, etc.

Full documentation for Pafy is here.

You can install Pafy with the command: pip install pafy

I tried out Pafy a little, and whatever I tried worked the way the docs said it would.

Here is a simple example of using Pafy to get info about a YouTube video and download it to your machine. I used the video 'Concurrency is not Parallelism' - by Rob Pike, co-inventor of the Go language, in the example. The video is also embedded below:



import pafy

# Concurrency is not parallelism - video URL = "https://www.youtube.com/watch?v=cN_DpYBzKso"
cinp_url = "https://www.youtube.com/watch?v=cN_DpYBzKso"

cinp_video = pafy.new(cinp_url)
cv = cinp_video

print "Info for video 'Concurrency is not Parallelism' by Rob Pike, Commander, Google:"
print 'Title:', cv.title
print 'Length:', cv.length
print 'Duration:', cv.duration
print 'Description:', cv.description

"""
This fragment prints info about the streams available in the video.
streams = cv.streams
for s in streams:
    print(s)
"""

# Get the best stream for the video.
best = cv.getbest()

# Download the best stream.
best.download(quiet=False, filepath=best.title + "." + best.extension)

The Pafy download() method not only downloads the video, it also shows the size downloaded so far as a percentage, the download speed, and the ETA for the download, in real time.

Also check out my earlier post on another YouTube tool in Python:

youtube-dl, a YouTube downloader in Python


- Vasudev Ram - Dancing Bison Enterprises - Python consulting and training

Contact Page

Friday, February 14, 2014

PyEmbed, a content embedding library for Python

By Vasudev Ram



Saw PyEmbed today via the Python Weekly email newsletter. PyEmbed is a Python library for embedding content in a web page. Given a URL of some content, it fetches the embed code for it, which you can then embed in an HTML page.

PyEmbed looks good on an initial try. I thought for a while about what video to test PyEmebed with, and finally settled on a YouTube video of the Indian film actress Rekha, in a famous dance scene in the film Umrao Jaan, which won her a National Film Award for Best Actress.

For all my readers who don't know Hindi (the movie is in Hindi), there are English subtitles at the bottom of the video.

PyEmbed is quite simple to use for basic usage, though it does have some advanced features.

Here is a simple Python program using PyEmbed to fetch the embed code for the Rekha dance video from the film Umrao Jaan described above:
from pyembed.core import PyEmbed
html = PyEmbed().embed('http://www.youtube.com/watch?feature=player_detailpage&v=3oFm4MYbb9o')
print html

I ran it with:

python test_pyembed.py

And then pasted the resulting HTML below to embed the video:

Rekha dancing in the movie Umrao Jaan




- Vasudev Ram - Dancing Bison Enterprises

Read other Python posts on my blog.

Contact Page



Thursday, July 9, 2009

Playing an MP3 with pyglet and Python is easy

By Vasudev Ram

pyglet is a cross-platform windowing and multimedia library for Python.

Playing an MP3 with pyglet and Python is as easy as this:

import pyglet

music = pyglet.resource.media('your_file.mp3')
music.play()

pyglet.app.run()

Some of the features of pyglet (from the pyglet site):

  • No external dependencies or installation requirements. For most application and game requirements, pyglet needs nothing else besides Python, simplifying distribution and installation.

  • Take advantage of multiple windows and multi-monitor desktops. pyglet allows you to use as many windows as you need, and is fully aware of multi-monitor setups for use with fullscreen games.

  • Load images, sound, music and video in almost any format. pyglet can optionally use AVbin to play back audio formats such as MP3, OGG/Vorbis and WMA, and video formats such as DivX, MPEG-2, H.264, WMV and Xvid.


Another good thing about pyglet is that it's a small download; also, installation went fast and without a hitch. Immediately after installing it (on Windows, with the bundled AVBin), I was able to run the above code. No configuration was required. AVbin is a thin wrapper around FFmpeg, which is a cross-platform solution to record, convert and stream audio and video.

I've not yet checked whether it's possible to pause and continue the played audio, though, either programmatically or via some graphical controls of pyglet.

UPDATE: Yes, GUI controls are possible. See the code for this audio and video player with simple GUI controls, in the link titled "examples/media_player.py" near the end of this page.

Currently listening to an MP3 of a tech interview that's being played by the above pyglet program.



- Vasudev Ram - Dancing Bison Enterprises.