Python Quickstart: Play an MP3 for the Caller

That's nice, now let's play the sound of a nice monkey howl for the caller after we greet them by name. To do that, use the Twilio <Play> verb.

This tutorial assumes you are running Flask on a server available over the Internet, and have the twilio-python library installed. If not, see our guide to setting up your local development environment.

Our Flask server file looks like this:

run.py
from flask import Flask, request, redirect
from twilio.twiml.voice_response import VoiceResponse


app = Flask(__name__)

callers = {
    "+14158675309": "Curious George",
    "+14158675310": "Boots",
    "+14158675311": "Virgil",
}

@app.route("/", methods=['GET', 'POST'])
def hello_monkey():
    """Say a caller's name, and play an MP3 for them."""

    from_number = request.values.get('From', None)
    if from_number in callers:
        caller = callers[from_number]
    else:
        caller = "Monkey"

    resp = VoiceResponse()
    # Greet the caller by name
    resp.say("Hello " + caller)
    # Play an MP3
    resp.play("http://demo.twilio.com/hellomonkey/monkey.mp3")

    return str(resp)

if __name__ == "__main__":
    app.run(debug=True)

The outputted TwiML will look something like this, if Curious George was the caller:

<?xml version="1.0" encoding="UTF-8"?>
<Response>
    <Say>Hello Curious George</Say>
    <Play>http://demo.twilio.com/hellomonkey/monkey.mp3</Play>
</Response>

Curious George would hear his name, and then hear an MP3 recording.


Next: Connect Call to Second Person »

Need some help?

We all do sometimes; code is hard. Get help now from our support team, or lean on the wisdom of the crowd browsing the Twilio tag on Stack Overflow.