ACRCloud
Search…
Identification API
Request this API you should use “multipart/form-data” Content-Type. You can use this API to identify all of the audio formats or fingerprint extracted with our SDK/Tools. We suggest you use data type “fingerprint”, which will reduce the internet bandwidth and accelerate recognition speeds. Also, we suggest you do not use a large file to request this API, this can cause delays, its advised to reduce the file size before upload, files that are less than 15 seconds are generally better.
post
https://identify-eu-west-1.acrcloud.com
/v1/identify
Identifying an audio file or a fingerprint file
Python
PHP
Java
Javascript
ReactNative
Ruby
1
2
"""
3
This is a demo program which implements ACRCloud Identify Protocol V1 with the third party library "requests".
4
We recomment you implement your own app with "requests" too.
5
You can install this python library by:
6
1) sudo easy_install requests
7
2) sudo pip install requests
8
"""
9
10
import base64
11
import hashlib
12
import hmac
13
import os
14
import sys
15
import time
16
17
import requests
18
19
'''
20
Replace "###...###" below with your project's host, access_key and access_secret.
21
'''
22
access_key = "###YOUR_ACCESS_KEY###"
23
access_secret = "###YOUR_ACCESS_SECRET###"
24
requrl = "http://###YOUR_HOST###/v1/identify"
25
26
http_method = "POST"
27
http_uri = "/v1/identify"
28
# default is "fingerprint", it's for recognizing fingerprint,
29
# if you want to identify audio, please change data_type="audio"
30
data_type = "audio"
31
signature_version = "1"
32
timestamp = time.time()
33
34
string_to_sign = http_method + "\n" + http_uri + "\n" + access_key + "\n" + data_type + "\n" + signature_version + "\n" + str(
35
timestamp)
36
37
sign = base64.b64encode(hmac.new(access_secret.encode('ascii'), string_to_sign.encode('ascii'),
38
digestmod=hashlib.sha1).digest()).decode('ascii')
39
40
# suported file formats: mp3,wav,wma,amr,ogg, ape,acc,spx,m4a,mp4,FLAC, etc
41
# File size: < 1M , You'de better cut large file to small file, within 15 seconds data size is better
42
f = open(sys.argv[1], "rb")
43
sample_bytes = os.path.getsize(sys.argv[1])
44
45
files = [
46
('sample', ('test.mp3', open('/Users/olym/Downloads/test.mp3', 'rb'), 'audio/mpeg'))
47
]
48
data = {'access_key': access_key,
49
'sample_bytes': sample_bytes,
50
'timestamp': str(timestamp),
51
'signature': sign,
52
'data_type': data_type,
53
"signature_version": signature_version}
54
55
r = requests.post(requrl, files=files, data=data)
56
r.encoding = "utf-8"
57
print(r.text)
Copied!
1
<?php
2
3
$http_method = "POST";
4
$http_uri = "/v1/identify";
5
$data_type = "audio";
6
$signature_version = "1" ;
7
$timestamp = time() ;
8
9
10
// Replace "###...###" below with your project's host, access_key and access_secret.
11
$requrl = "http://###YOUR_HOST###/v1/identify";
12
$access_key = '###YOUR_ACCESS_KEY###';
13
$access_secret = '###YOUR_ACCESS_SECRET###';
14
15
$string_to_sign = $http_method . "\n" .
16
$http_uri ."\n" .
17
$access_key . "\n" .
18
$data_type . "\n" .
19
$signature_version . "\n" .
20
$timestamp;
21
$signature = hash_hmac("sha1", $string_to_sign, $access_secret, true);
22
23
$signature = base64_encode($signature);
24
25
// suported file formats: mp3,wav,wma,amr,ogg, ape,acc,spx,m4a,mp4,FLAC, etc
26
// File size: < 1M , You'de better cut large file to small file, within 15 seconds data size is better
27
$file = $argv[1];
28
$filesize = filesize($file);
29
$cfile = new CURLFile($file, "mp3", basename($argv[1]));
30
31
$postfields = array(
32
"sample" => $cfile,
33
"sample_bytes"=>$filesize,
34
"access_key"=>$access_key,
35
"data_type"=>$data_type,
36
"signature"=>$signature,
37
"signature_version"=>$signature_version,
38
"timestamp"=>$timestamp);
39
40
$ch = curl_init();
41
curl_setopt($ch, CURLOPT_URL, $requrl);
42
curl_setopt($ch, CURLOPT_POST, true);
43
curl_setopt($ch, CURLOPT_POSTFIELDS, $postfields);
44
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
45
46
$result = curl_exec($ch);
47
echo $result;
48
//$response = curl_exec($ch);
49
//if ($response == true) {
50
// $info = curl_getinfo($ch);
51
//} else {
52
// $errmsg = curl_error($ch);
53
// print $errmsg;
54
//}
55
curl_close($ch);
56
?>
Copied!
1
import java.io.BufferedOutputStream;
2
import java.io.BufferedReader;
3
import java.io.ByteArrayOutputStream;
4
import java.io.File;
5
import java.io.FileInputStream;
6
import java.io.IOException;
7
import java.io.InputStreamReader;
8
import java.net.HttpURLConnection;
9
import java.net.URL;
10
import java.util.Calendar;
11
import java.util.HashMap;
12
import java.util.Map;
13
import javax.crypto.Mac;
14
import javax.crypto.spec.SecretKeySpec;
15
16
// import commons-codec-<version>.jar, download from http://commons.apache.org/proper/commons-codec/download_codec.cgi
17
import org.apache.commons.codec.binary.Base64;
18
19
public class IdentifyProtocolV1 {
20
21
private String encodeBase64(byte[] bstr) {
22
Base64 base64 = new Base64();
23
return new String(base64.encode(bstr));
24
}
25
26
private String encryptByHMACSHA1(byte[] data, byte[] key) {
27
try {
28
SecretKeySpec signingKey = new SecretKeySpec(key, "HmacSHA1");
29
Mac mac = Mac.getInstance("HmacSHA1");
30
mac.init(signingKey);
31
byte[] rawHmac = mac.doFinal(data);
32
return encodeBase64(rawHmac);
33
} catch (Exception e) {
34
e.printStackTrace();
35
}
36
return "";
37
}
38
39
private String getUTCTimeSeconds() {
40
Calendar cal = Calendar.getInstance();
41
int zoneOffset = cal.get(Calendar.ZONE_OFFSET);
42
int dstOffset = cal.get(Calendar.DST_OFFSET);
43
cal.add(Calendar.MILLISECOND, -(zoneOffset + dstOffset));
44
return cal.getTimeInMillis()/1000 + "";
45
}
46
47
private String postHttp(String posturl, Map<String, Object> params, int timeOut) {
48
String res = "";
49
String BOUNDARYSTR = "*****2015.03.30.acrcloud.rec.copyright." + System.currentTimeMillis() + "*****";
50
String BOUNDARY = "--" + BOUNDARYSTR + "\r\n";
51
String ENDBOUNDARY = "--" + BOUNDARYSTR + "--\r\n\r\n";
52
53
String stringKeyHeader = BOUNDARY +
54
"Content-Disposition: form-data; name=\"%s\"" +
55
"\r\n\r\n%s\r\n";
56
String filePartHeader = BOUNDARY +
57
"Content-Disposition: form-data; name=\"%s\"; filename=\"%s\"\r\n" +
58
"Content-Type: application/octet-stream\r\n\r\n";
59
60
URL url = null;
61
HttpURLConnection conn = null;
62
BufferedOutputStream out = null;
63
BufferedReader reader = null;
64
ByteArrayOutputStream postBufferStream = new ByteArrayOutputStream();
65
try {
66
for (String key : params.keySet()) {
67
Object value = params.get(key);
68
if (value instanceof String || value instanceof Integer) {
69
postBufferStream.write(String.format(stringKeyHeader, key, (String)value).getBytes());
70
} else if (value instanceof byte[]) {
71
postBufferStream.write(String.format(filePartHeader, key, key).getBytes());
72
postBufferStream.write((byte[]) value);
73
postBufferStream.write("\r\n".getBytes());
74
}
75
}
76
postBufferStream.write(ENDBOUNDARY.getBytes());
77
78
url = new URL(posturl);
79
conn = (HttpURLConnection) url.openConnection();
80
conn.setConnectTimeout(timeOut);
81
conn.setReadTimeout(timeOut);
82
conn.setRequestMethod("POST");
83
conn.setDoOutput(true);
84
conn.setDoInput(true);
85
conn.setRequestProperty("Accept-Charset", "utf-8");
86
conn.setRequestProperty("Content-type", "multipart/form-data;boundary=" + BOUNDARYSTR);
87
88
conn.connect();
89
out = new BufferedOutputStream(conn.getOutputStream());
90
out.write(postBufferStream.toByteArray());
91
out.flush();
92
int response = conn.getResponseCode();
93
if (response == HttpURLConnection.HTTP_OK) {
94
reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "UTF-8"));
95
String tmpRes = "";
96
while ((tmpRes = reader.readLine()) != null) {
97
if (tmpRes.length() > 0)
98
res = res + tmpRes;
99
}
100
}
101
} catch (Exception e) {
102
e.printStackTrace();
103
} finally {
104
try {
105
if (postBufferStream != null) {
106
postBufferStream.close();
107
postBufferStream = null;
108
}
109
if (out != null) {
110
out.close();
111
out = null;
112
}
113
if (reader != null) {
114
reader.close();
115
reader = null;
116
}
117
if (conn != null) {
118
conn.disconnect();
119
conn = null;
120
}
121
} catch (IOException e) {
122
e.printStackTrace();
123
}
124
}
125
return res;
126
}
127
128
public String recognize(String host, String accessKey, String secretKey, byte[] queryData, String queryType, int timeout)
129
{
130
String method = "POST";
131
String httpURL = "/v1/identify";
132
String dataType = queryType;
133
String sigVersion = "1";
134
String timestamp = getUTCTimeSeconds();
135
136
String reqURL = "http://" + host + httpURL;
137
138
String sigStr = method + "\n" + httpURL + "\n" + accessKey + "\n" + dataType + "\n" + sigVersion + "\n" + timestamp;
139
String signature = encryptByHMACSHA1(sigStr.getBytes(), secretKey.getBytes());
140
141
Map<String, Object> postParams = new HashMap<String, Object>();
142
postParams.put("access_key", accessKey);
143
postParams.put("sample_bytes", queryData.length + "");
144
postParams.put("sample", queryData);
145
postParams.put("timestamp", timestamp);
146
postParams.put("signature", signature);
147
postParams.put("data_type", queryType);
148
postParams.put("signature_version", sigVersion);
149
150
String res = postHttp(reqURL, postParams, timeout);
151
152
return res;
153
}
154
155
public static void main(String[] args) {
156
File file = new File("E://sample.wav");
157
byte[] buffer = new byte[1024 * 1024];
158
if (!file.exists()) {
159
return;
160
}
161
FileInputStream fin = null;
162
int bufferLen = 0;
163
try {
164
fin = new FileInputStream(file);
165
bufferLen = fin.read(buffer, 0, buffer.length);
166
} catch (Exception e) {
167
e.printStackTrace();
168
} finally {
169
try {
170
if (fin != null) {
171
fin.close();
172
}
173
} catch (IOException e) {
174
e.printStackTrace();
175
}
176
}
177
System.out.println("bufferLen=" + bufferLen);
178
179
if (bufferLen <= 0)
180
return;
181
182
byte[] postDatas = new byte[bufferLen];
183
System.arraycopy(buffer, 0, postDatas, 0, bufferLen);
184
IdentifyProtocolV1 a = new IdentifyProtocolV1();
185
186
// Replace "###...###" below with your project's host, access_key and access_secret.
187
// recognize(String host, String accessKey, String secretKey, byte[] queryData, String queryType, int timeout)
188
String result = a.recognize("###YOUR_HOST###", "###YOUR_KEY###", "###YOUR_SECRET###", postDatas, "audio", 10000);
189
System.out.println(result);
190
}
191
}
Copied!
1
var url = require('url');
2
var fs = require('fs');
3
var crypto = require('crypto');
4
//npm install request
5
var request = require('request');
6
7
// Replace "###...###" below with your project's host, access_key and access_secret.
8
var defaultOptions = {
9
host: '###YOUR_HOST###',
10
endpoint: '/v1/identify',
11
signature_version: '1',
12
data_type:'audio',
13
secure: true,
14
access_key: '###YOUR_ACCESS_KEY###',
15
access_secret: '###YOUR_ACCESS_SECRET###'
16
};
17
18
function buildStringToSign(method, uri, accessKey, dataType, signatureVersion, timestamp) {
19
return [method, uri, accessKey, dataType, signatureVersion, timestamp].join('\n');
20
}
21
22
function sign(signString, accessSecret) {
23
return crypto.createHmac('sha1', accessSecret)
24
.update(Buffer.from(signString, 'utf-8'))
25
.digest().toString('base64');
26
}
27
28
/**
29
* Identifies a sample of bytes
30
*/
31
function identify(data, options, cb) {
32
33
var current_data = new Date();
34
var timestamp = current_data.getTime()/1000;
35
36
var stringToSign = buildStringToSign('POST',
37
options.endpoint,
38
options.access_key,
39
options.data_type,
40
options.signature_version,
41
timestamp);
42
43
var signature = sign(stringToSign, options.access_secret);
44
45
var formData = {
46
sample: data,
47
access_key:options.access_key,
48
data_type:options.data_type,
49
signature_version:options.signature_version,
50
signature:signature,
51
sample_bytes:data.length,
52
timestamp:timestamp,
53
}
54
request.post({
55
url: "http://"+options.host + options.endpoint,
56
method: 'POST',
57
formData: formData
58
}, cb);
59
}
60
61
function identify_v2(data, options, cb) {
62
//npm install form-data
63
var FormData = require('form-data');
64
//npm install node-fetch
65
var fetch = require('node-fetch');
66
67
var current_data = new Date();
68
var timestamp = current_data.getTime()/1000;
69
70
var stringToSign = buildStringToSign('POST',
71
options.endpoint,
72
options.access_key,
73
options.data_type,
74
options.signature_version,
75
timestamp);
76
77
var signature = sign(stringToSign, options.access_secret);
78
79
var form = new FormData();
80
form.append('sample', data);
81
form.append('sample_bytes', data.length);
82
form.append('access_key', options.access_key);
83
form.append('data_type', options.data_type);
84
form.append('signature_version', options.signature_version);
85
form.append('signature', signature);
86
form.append('timestamp', timestamp);
87
88
fetch("http://"+options.host + options.endpoint,
89
{method: 'POST', body: form })
90
.then((res) => {return res.text()})
91
.then((res) => {cb(res, null)})
92
.catch((err) => {cb(null, err)});
93
}
94
95
var bitmap = fs.readFileSync('sample.wav');
96
97
identify(Buffer.from(bitmap), defaultOptions, function (err, httpResponse, body) {
98
if (err) console.log(err);
99
console.log(body);
100
});
Copied!
1
import React from 'react';
2
import {StyleSheet, Button, View, Text} from 'react-native';
3
import {Audio} from 'expo-av';
4
import {FileSystem, Permissions} from 'react-native-unimodules';
5
import hmacSHA1 from 'crypto-js/hmac-sha1';
6
import Base64 from 'crypto-js/enc-base64';
7
import {Buffer} from 'buffer';
8
9
export default class MusicRec_Test extends React.Component {
10
constructor(props) {
11
super(props);
12
this.state = {response: ''};
13
}
14
async _findSong() {
15
// Audio.setAudioModeAsync()
16
const {status} = await Audio.requestPermissionsAsync();
17
console.log('Current Status ' + status);
18
const recording = new Audio.Recording();
19
try {
20
await Audio.setAudioModeAsync({
21
playsInSilentModeIOS: true,
22
allowsRecordingIOS: true,
23
});
24
const recordOptions = {
25
android: {
26
extension: '.m4a',
27
outputFormat: Audio.RECORDING_OPTION_ANDROID_OUTPUT_FORMAT_MPEG_4,
28
audioEncoder: Audio.RECORDING_OPTION_ANDROID_AUDIO_ENCODER_AAC,
29
sampleRate: 44100,
30
numberOfChannels: 2,
31
bitRate: 128000,
32
},
33
ios: {
34
extension: '.wav',
35
audioQuality: Audio.RECORDING_OPTION_IOS_AUDIO_QUALITY_HIGH,
36
sampleRate: 8000,
37
numberOfChannels: 1,
38
linearPCMBitDepth: 16,
39
linearPCMIsBigEndian: false,
40
linearPCMIsFloat: true,
41
},
42
};
43
await recording.prepareToRecordAsync(recordOptions);
44
await recording.startAsync();
45
console.log('Recording');
46
await timeout(8000);
47
console.log('Done recording');
48
await recording.stopAndUnloadAsync();
49
let recordingFile = recording.getURI();
50
51
let result = await identify(recordingFile, defaultOptions);
52
console.log(result);
53
//return result;
54
} catch (error) {
55
console.log(error);
56
console.log('Error in this!!!!');
57
}
58
}
59
render() {
60
return (
61
<View style={styles.container}>
62
<Button title="Find Song" onPress={this._findSong} />
63
<Text />
64
</View>
65
);
66
}
67
}
68
function timeout(ms) {
69
return new Promise(resolve => setTimeout(resolve, ms));
70
}
71
const defaultOptions = {
72
host: '<Project Host>',
73
endpoint: '/v1/identify',
74
signature_version: '1',
75
data_type: 'audio',
76
secure: true,
77
access_key: '<Project AccessKey>',
78
access_secret: '<Project SecretKey>',
79
};
80
function buildStringToSign(
81
method,
82
uri,
83
accessKey,
84
dataType,
85
signatureVersion,
86
timestamp,
87
) {
88
return [method, uri, accessKey, dataType, signatureVersion, timestamp].join(
89
'\n',
90
);
91
}
92
function signString(stringToSign, accessSecret) {
93
return Base64.stringify(hmacSHA1(stringToSign, accessSecret));