Skip to content

Sample Code

The following is some sample code that provides an example of performing a basic "identify music" audio search.

#!/usr/bin/env python3

import json
import pex

CLIENT_ID = "#YOUR_CLIENT_ID_HERE"
CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE"
INPUT_FILE = "/path/to/file.mp3"

def main():
    # Initialize and authenticate the client
    client = pex.PexSearchClient(CLIENT_ID, CLIENT_SECRET)

    # Create an audio fingerprint from input file
    ft = client.fingerprint_file(INPUT_FILE, pex.FingerprintType.AUDIO)

    # Build an identify music search request
    req = pex.PexSearchRequest(fingerprint=ft, type=pex.PexSearchType.IDENTIFY_MUSIC)

    # Perform the lookup
    result = do_lookup(client, req)

    # Print the result
    print(json.dumps(result, indent=2))


def do_lookup(client, req):
    while True:
        try:
            # Start the search
            future = client.start_search(req)

            # Return the result
            return future.get()

        except pex.Error as err:
            # Raise the error if it's not retryable
            if not err.is_retryable:
                raise err

            # Log the error
            print(err)
            print("retrying lookup...")

            # Sleep for 1s or use exponential backoff
            time.sleep(1)

            # Retry the lookup
            continue

if __name__ == '__main__':
    main()
package main

import (
    "encoding/json"
    "fmt"

    pex "github.com/Pexeso/pex-sdk-go/v4"
)

const (
    clientID     = "#YOUR_CLIENT_ID_HERE"
    clientSecret = "#YOUR_CLIENT_SECRET_HERE"
    inputFile    = "/path/to/file.mp3"
)

func main() {
    // Initialize and authenticate the client
    client, err := pex.NewPexSearchClient(clientID, clientSecret)
    if err != nil {
        panic(err)
    }
    defer client.Close()

    // Create an audio fingerprint from input file
    ft, err := client.FingerprintFile(inputFile, pex.FingerprintTypeAudio)
    if err != nil {
        panic(err)
    }

    // Build an identify music search request
    req := &pex.PexSearchRequest{
        Fingerprint: ft,
        Type:        pex.IdentifyMusic,
    }

    // Perform the lookup
    res, err := doLookup(client, req)
    if err != nil {
        panic(err)
    }

    // Print the result
    j, err := json.MarshalIndent(res, "", "  ")
    if err != nil {
        panic(err)
    }
    fmt.Println(string(j))
}

func doLookup(client *pex.PexSearchClient, req *pex.PexSearchRequest) (*pex.PexSearchResult, error) {
  for {
    // Start the search
    fut, err := client.StartSearch(req)
    if err != nil {
      if isFatal(err) {
        return nil, err
      }

      // Retry the lookup
      continue
    }

    // Retrieve the result
    res, err := fut.Get()
    if err != nil {
      if isFatal(err) {
        return nil, err
      }

      // Retry the lookup
      continue
    }

    return res, nil
  }
}

func isFatal(err error) bool {
  pexErr, ok := err.(*pex.Error)
  if !ok {
    return true
  }

  if !pexErr.IsRetryable {
    return true
  }

  // Log the error
  fmt.Println(err)
  fmt.Println("retrying lookup...")

  // Sleep for 1s or use exponential backoff
  time.Sleep(time.Second)

  return false
}
<?php

require __DIR__ . '/vendor/autoload.php';

const CLIENT_ID = "#YOUR_CLIENT_ID_HERE";
const CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE";
const INPUT_FILE = "/path/to/file.mp3";

function main() {
  // Initialize and authenticate the client
  $client = new Pex\PexSearchClient(CLIENT_ID, CLIENT_SECRET);

  // Create an audio fingerprint from input file
  $ft = $client->fingerprintFile(INPUT_FILE, [Pex\FingerprintType::Audio]);

  // Build an identify music search request
  $req = new Pex\PexSearchRequest($ft, $type=Pex\PexSearchType::IdentifyMusic);

  // Perform the lookup
  $res = doLookup($client, $req);

  // Print the result
  var_dump($res);
}

function doLookup($client, $req) {
  while (true) {
    try {
      // Start the search
      $fut = $client->startSearch($req);

      // Retrieve the result
      return $fut->get();
    } catch (Pex\Error $err) {
      // Rethrow the error if it's not retryable
      if (!$err->isRetryable()) {
        throw $err;
      }

      // Log the error
      echo $err, "\n";
      echo "retrying lookup...\n";

      // Sleep for 1s or use exponential backoff
      sleep(1);

      // Retry the lookup
      continue;
    }
  }
}

main();
const pex = require("pex-sdk");

const CLIENT_ID = "#YOUR_CLIENT_ID_HERE";
const CLIENT_SECRET = "#YOUR_CLIENT_SECRET_HERE";
const INPUT_FILE = "/path/to/file.mp3";

async function main() {
  // Initialize and authenticate the client
  let client = new pex.PexSearchClient(CLIENT_ID, CLIENT_SECRET)

  // Connect to the PexSearch server. This operation is asynchronous and
  // returns a promise, just like most operations in this package.
  await client.connect()

  // Create an audio fingerprint from input file
  let ft = await client.fingerprintFile(INPUT_FILE, [pex.AUDIO])

  // Perform an identify music search and await the result
  let result = await doLookup(client, {
    fingerprint: ft,
    type: pex.IDENTIFY_MUSIC,
  })

  // Pretty print the result
  console.log(JSON.stringify(result, null, 2))
}

async function doLookup(client, req) {
  while(true) {
    try {
      // Start the search
      let fut = client.startSearch(req)

      // Retrieve the result
      return await fut;
    } catch(err) {
      // Rethrow the error if it's not retryable
      if (!err.isRetryable) {
        throw err
      }

      // Log the error
      console.log(err)
      console.log("retrying lookup...")

      // Sleep for 1s or use exponential backoff
      await new Promise(r => setTimeout(r, 1000))

      // Retry the lookup
      continue
    }
  }
}

main()