Play MP3 for Caller



Let us see how to make your calls more customised by playing a configurated MP3 file after you have answered the call. Of course you need to install API Extension and subscribe to Incoming Call URL with your application’s URL.
Let us see how to make your calls more customised by playing a configurated MP3 file after you have answered the call. First of all, please login and connect to the API Extension. Wait for an Incoming call, and when it is occured just attach into the call a WaveStreamPlayer object and add the path of your audio file.


Example code coming soon...
[HttpPost]
public ActionResult PlayMP3(string notificationName, string callLegID, string caller, string apiExtension)
{
	return Content(
   "<Response>" +
		"<Play Repeat=\"false\">http://yoursite.com/welcome.mp3</Play>" + //Please add valid MP3 file
   "</Response>", "text/xml");
}
class PlayMp3Controller < ApplicationController

  protect_from_forgery except: :index

  # In routes.rb you need to set the following routing rule
  # post '/play_mp3' => 'play_mp3#index'

  def index

    render :xml => '<?xml version="1.0" encoding="UTF-8"?>
    <Response>
      <Play Repeat="false">http://yoursite.com/welcome.mp3</Play>
    </Response>'
  end

end
<?php
	print "<Response>";
		print "<Play Repeat=\"false\"> http://yoursite.com/welcome.mp3</Play>";
	print "</Response>";
?>
#!c:/Perl64/bin/perl.exe   
print "Content-Type: text/plain\n\n";
#You have to add the directory route of perl.exe, and print the content type

#Send response by print
print 
'<?xml version="1.0" encoding="UTF-8"?>
<Response>
	<Play Repeat="false">http://yoursite.com/welcome.mp3</Play>
</Response>'
Imports Ozeki.Media.MediaHandlers
Imports OPSSDKCommon.Model.Call
Imports OPSSDK
Imports Ozeki.VoIP

Module Module1
    Public Sub Main(args As String())
        Dim client = New OpsClient()
        AddHandler client.ErrorOccurred, Sub(sender, info)
                                             Console.WriteLine(info.Message)
                                         End Sub

        If Not client.Login("ozekixepbx.ip", "admin", "12345") Then
            Return
        End If

        Dim apiExtension = client.GetAPIExtension("9000")
        AddHandler apiExtension.IncomingCall, AddressOf IncomingCall
        Console.ReadLine()
    End Sub

    Private Sub IncomingCall(sender As Object, e As VoIPEventArgs(Of ICall))
        Dim [call] = e.Item
        Dim waveStreamPlayback = New WaveStreamPlayback("c://hello.wav", False, False)
        [call].ConnectAudioSender(waveStreamPlayback)

        AddHandler waveStreamPlayback.Stopped, Sub(s, ev)
                                                   [call].HangUp()
                                               End Sub

        AddHandler [call].CallStateChanged,
            Sub(s, ev)
                If ev.Item = CallState.Answered Then
                    waveStreamPlayback.StartStreaming()
                ElseIf ev.Item.IsCallEnded() Then
                    waveStreamPlayback.Dispose()
                End If
            End Sub

        [call].Accept()
    End Sub
End Module
def application(environ, start_response):
    
    filePath = "http://yoursite.com/welcome.mp3"
    
    result = """<?xml version="1.0" encoding="UTF-8"?>
        <Response>
            <Play Repeat="false">{0}</Play>
        </Response>""".format(filePath)
        
    response_headers = [('Content-type', 'text/plain'), ('Content-Length', str(len(result)))]
    start_response('200 OK', response_headers)

    return [result]
using System;
using OPSSDK;
using OPSSDKCommon.Model.Call;
using Ozeki.Media.MediaHandlers;
using Ozeki.VoIP;

namespace OPS_QuickStartExample_CSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            var client = new OpsClient();
            client.ErrorOccurred += (sender, info) =>
                Console.WriteLine(info.Message);

            if (!client.Login("ozekixepbx.ip", "admin", "12345"))
                return;

            var apiExtension = client.GetAPIExtension("9000");
            apiExtension.IncomingCall += IncomingCall;
            Console.ReadLine();
        }

        private static void IncomingCall(object sender, VoIPEventArgs e)
        {
            var call = e.Item;
            var waveStreamPlayback = new WaveStreamPlayback("c://hello.wav", false, false);
            call.ConnectAudioSender(waveStreamPlayback);
            waveStreamPlayback.Stopped += (s, a) => call.HangUp();

            call.CallStateChanged += (s, ev) =>
            {
                if (ev.Item == CallState.Answered)
                    waveStreamPlayback.StartStreaming();
                else if (ev.Item.IsCallEnded())
                    waveStreamPlayback.Dispose();
            };

            call.Accept();
        }
    }
}
package pbxsampleapp;

import com.sun.net.httpserver.*;
import java.io.*;
import java.net.*;

public class PlayAudioFileForCaller 
{
  public static void main(String[] args)
    {
        try
        {
            System.out.println("Starting http server...");
            HttpServer server = HttpServer.create(new InetSocketAddress(InetAddress.getByAddress(new byte[]{ 0, 0, 0, 0 }), 12345), 0);
            server.createContext("/playaudio", new PbxSampleApp.PBXRequestHandler());
            server.start();
            System.out.println("http server running on " + server.getAddress().toString());
        }
        catch (IOException ex) { System.out.println("Error" + ex.toString()); }
    }

    static class PBXRequestHandler implements HttpHandler
    {
        @Override
        public void handle(HttpExchange httpExchange) throws IOException
        {
            httpExchange.getResponseHeaders().add("Content-type", "text/xml");
            String response = 
                "<?xml version=\"1.0\"?>"
                + "<Response>"
                + "<Play Repeat=\"false\">http://yoursite.com/welcome.mp3</Play>"
                + "</Response>";
            httpExchange.sendResponseHeaders(200, response.length());
            OutputStream os = httpExchange.getResponseBody();
            os.write(response.getBytes());
            os.close();
        }
    }
}
Code example 1 - Play MP3 for the caller

IN MORE DETAILS

First of all, please put an MP3 (or Wav) file to the right directory at your web server. Please change the yoursite.com text to that ip address where the sample applications are running. However, it is possible to use an online file too. This file will be played for the caller.

The program will send back the OzML response to the caller. As you can see, it is just a simple Play command. Please write your file path between the <Play> and </Play> tags.
IN MORE DETAILS

Get the OPSSDK.dll

First you need to add the OPSSDK.dll reference to your project
(You can find OPSSDK.dll at C:\Program Files\Ozeki\Ozeki Phone System\Examples\.NET API\OPSSDK.dll).

Login and connect

Create a new instance of OpsClient, and subscribe to the ErrorOccurred event. Your program will communicate with the Ozeki Phone System through this client. Try to login with the client into the running Ozeki Phone System, with the address of the server(ozekixepbx.ip) and a valid username, password combination.

If you are ready, try to get an existing API Extension, with the GetApiExtension method of the OpsClient. Read more about installation of API Extension.

Further steps

When you are ready with the initial steps above, subscribe the IncomingCall event of the apiExtension. This event will be triggered every time when the selected API Extension is called. In the mentioned event handler you will see the e.Item paramter, this parameter will be the call object. This call object has a CallState property, when the CallState is Ringing subscribe the CallStateChanged event of the call object and Accept the call.

The CallStateChanged event will trigger when the call is going to another state . When the CallState is Answered, you can connect the devices to the call. When the call has ended, please do not forget to disconnect all devices from the call.

When the CallState is Answered, start and connect to the call a WaveStreamPlayback object, what will play to the caller the given audio file. When the WaveStreamPlayback is finished the call will hung up.

With these steps, you learnt how to receive an incoming call, and play an audio file to the caller.

More information