A couple of days ago I encountered this article: How Shazam Works
This got me interested in how a program like Shazam works… And more importantly, how hard is it to program something similar in Java?
About Shazam
Shazam is an application which you can use to analyse/match music. When you install it on your phone, and hold the microphone to some music for about 20 to 30 seconds, it will tell you which song it is.
When I first used it it gave me a magical feeling. “How did it do that!?”. And even today, after using it a lot, it still has a bit of magical feel to it.
Wouldn’t it be great if we can program something of our own that gives that same feeling? That was my goal for the past weekend.
Listen up..!
First things first, get the music sample to analyse we first need to listen to the microphone in our Java application…! This is something I hadn’t done yet in Java, so I had no idea how hard this was going to be.
But it turned out it was very easy:
1 |
final AudioFormat format = getFormat(); //Fill AudioFormat with the wanted settings |
2 |
DataLine.Info info = new DataLine.Info(TargetDataLine.class, format); |
3 |
final TargetDataLine line = (TargetDataLine) AudioSystem.getLine(info); |
Now we can read the data from the TargetDataLine just like a normal InputStream:
01 |
// In another thread I start: |
03 |
OutputStream out = new ByteArrayOutputStream(); |
08 |
int count = line.read(buffer, 0, buffer.length); |
10 |
out.write(buffer, 0, count); |
14 |
} catch (IOException e) { |
15 |
System.err.println("I/O problems: " + e); |
Using this method it is easy to open the microphone and record all the sounds! The AudioFormat I’m currently using is:
1 |
private AudioFormat getFormat() { |
2 |
float sampleRate = 44100; |
3 |
int sampleSizeInBits = 8; |
4 |
int channels = 1; //mono |
6 |
boolean bigEndian = true; |
7 |
return new AudioFormat(sampleRate, sampleSizeInBits, channels, signed, bigEndian); |
So, now we have the recorded data in a ByteArrayOutputStream, great! Step 1 complete.
Microphone data
The next challenge is analyzing the data, when I outputted the data I received in my byte array I got a long list of numbers, like this:
Erhm… yes? This is sound?
To see if the data could be visualized I took the output and placed it in Open Office to generate a line graph:

Ah yes! This kind of looks like ‘sound’. It looks like what you see when using for example Windows Sound Recorder.
This data is actually known as time domain. But these numbers are currently basically useless to us… if you read the above article on how Shazam works you’ll read that they use a spectrum analysis instead of direct time domain data.
So the next big question is: How do we transform the current data into a spectrum analysis?
Discrete Fourier transform
To turn our data into usable data we need to apply the so called Discrete Fourier Transformation. This turns the data from time domain into frequency domain.
There is just one problem, if you transform the data into the frequency domain you loose every bit of information regarding time. So you’ll know what the magnitude of all the frequencies are, but you have no idea when they appear.
To solve this we need a sliding window. We take chunks of data (in my case 4096 bytes of data) and transform just this bit of information. Then we know the magnitude of all frequencies that occur during just these 4096 bytes.
Implementing this
Instead of worrying about the Fourier Transformation I googled a bit and found code for the so called FFT (Fast Fourier Transformation). I’m calling this code with the chunks:
01 |
byte audio[] = out.toByteArray(); |
03 |
final int totalSize = audio.length; |
05 |
int amountPossible = totalSize/Harvester.CHUNK_SIZE; |
07 |
//When turning into frequency domain we'll need complex numbers: |
08 |
Complex[][] results = new Complex[amountPossible][]; |
11 |
for(int times = 0;times < amountPossible; times++) { |
12 |
Complex[] complex = new Complex[Harvester.CHUNK_SIZE]; |
13 |
for(int i = 0;i < Harvester.CHUNK_SIZE;i++) { |
14 |
//Put the time domain data into a complex number with imaginary part as 0: |
15 |
complex[i] = new Complex(audio[(times*Harvester.CHUNK_SIZE)+i], 0); |
17 |
//Perform FFT analysis on the chunk: |
18 |
results[times] = FFT.fft(complex); |
Now we have a double array containing all chunks as Complex[]. This array contains data about all frequencies. To visualize this data I decided to implement a full spectrum analyzer (just to make sure I got the math right).
To show the data I hacked this together:
01 |
for(int i = 0; i < results.length; i++) { |
03 |
for(int line = 1; line < size; line++) { |
04 |
// To get the magnitude of the sound at a given frequency slice |
05 |
// get the abs() from the complex number. |
06 |
// In this case I use Math.log to get a more managable number (used for color) |
07 |
double magnitude = Math.log(results[i][freq].abs()+1); |
09 |
// The more blue in the color the more intensity for a given frequency point: |
10 |
g2d.setColor(new Color(0,(int)magnitude*10,(int)magnitude*20)); |
12 |
g2d.fillRect(i*blockSizeX, (size-line)*blockSizeY,blockSizeX,blockSizeY); |
14 |
// I used a improviced logarithmic scale and normal scale: |
15 |
if (logModeEnabled && (Math.log10(line) * Math.log10(line)) > 1) { |
16 |
freq += (int) (Math.log10(line) * Math.log10(line)); |
Introducing, Aphex Twin
This seems a bit of OT (off-topic), but I’d like to tell you about a electronic musician called Aphex Twin (Richard David James). He makes crazy electronic music… but some songs have an interesting feature. His biggest hit for example, Windowlicker has a spectrogram image in it.
If you look at the song as spectral image it shows a nice spiral. Another song, called ‘Mathematical Equation’ shows the face of Twin! More information can be found here: Bastwood – Aphex Twin’s face.
When running this song against my spectral analyzer I get the following result:

Not perfect, but it seems to be Twin’s face!
Determining the key music points
The next step in Shazam’s algorithm is to determine some key points in the song, save those points as a hash and then try to match on them against their database of over 8 million songs. This is done for speed, the lookup of a hash is O(1) speed. That explains a lot of the awesome performance of Shazam!
Because I wanted to have everything working in one weekend (this is my maximum attention span sadly enough, then I need a new project to work on) I kept my algorithm as simple as possible. And to my surprise it worked.
For each line the in spectrum analysis I take the points with the highest magnitude from certain ranges. In my case: 40-80, 80-120, 120-180, 180-300.
01 |
//For every line of data: |
03 |
for (int freq = LOWER_LIMIT; freq < UPPER_LIMIT-1; freq++) { |
05 |
double mag = Math.log(results[freq].abs() + 1); |
07 |
//Find out which range we are in: |
08 |
int index = getIndex(freq); |
10 |
//Save the highest magnitude and corresponding frequency: |
11 |
if (mag > highscores[index]) { |
12 |
highscores[index] = mag; |
13 |
recordPoints[index] = freq; |
17 |
//Write the points to a file: |
18 |
for (int i = 0; i < AMOUNT_OF_POINTS; i++) { |
19 |
fw.append(recordPoints[i] + "\t"); |
26 |
public static final int[] RANGE = new int[] {40,80,120,180, UPPER_LIMIT+1}; |
28 |
//Find out in which range |
29 |
public static int getIndex(int freq) { |
31 |
while(RANGE[i] < freq) i++; |
When we record a song now, we get a list of numbers such as:
If I record a song and look at it visually it looks like this:

(all the red dots are ‘important points’)
Indexing my own music
With this algorithm in place I decided to index all my 3000 songs. Instead of using the microphone you can just open mp3 files, convert them to the correct format, and read them the same way we did with the microphone, using an AudioInputStream. Converting stereo music into mono-channel audio was a bit trickier then I hoped. Examples can be found online (requires a bit too much code to paste here) have to change the sampling a bit.
Matching!
The most important part of the program is the matching process. Reading Shazams paper they use hashing to get matches and the decide which song was the best match.
Instead of using difficult point-groupings in time I decided to use a line of our data (for example “33, 47, 94, 137″) as one hash: 1370944733
(in my tests using 3 or 4 points works best, but tweaking is difficult, I need to re-index my mp3 every time!)
Example hash-code using 4 points per line:
01 |
//Using a little bit of error-correction, damping |
02 |
private static final int FUZ_FACTOR = 2; |
04 |
private long hash(String line) { |
05 |
String[] p = line.split("\t"); |
06 |
long p1 = Long.parseLong(p[0]); |
07 |
long p2 = Long.parseLong(p[1]); |
08 |
long p3 = Long.parseLong(p[2]); |
09 |
long p4 = Long.parseLong(p[3]); |
10 |
return (p4-(p4%FUZ_FACTOR)) * 100000000 + (p3-(p3%FUZ_FACTOR)) * 100000 + (p2-(p2%FUZ_FACTOR)) * 100+ (p1-(p1%FUZ_FACTOR)); |
Now I create two data sets:
– A list of songs, List<String> (List index is Song-ID, String is songname)
– Database of hashes: Map<Long, List<DataPoint>>
The long in the database of hashes represents the hash itself, and it has a bucket of DataPoints.
A DataPoint looks like:
01 |
private class DataPoint { |
06 |
public DataPoint(int songId, int time) { |
11 |
public int getTime() { |
14 |
public int getSongId() { |
Now we already have everything in place to do a lookup. First I read all the songs and generate hashes for each point of data. This is put into the hash-database.
The second step is reading the data of the song we need to match. These hashes are retrieved and we look at the matching datapoints.
There is just one problem, for each hash there are some hits, but how do we determine which song is the correct song..? Looking at the amount of matches? No, this doesn’t work…
The most important thing is timing. We must overlap the timing…! But how can we do this if we don’t know where we are in the song? After all, we could just as easily have recorded the final chords of the song.
By looking at the data I discovered something interesting, because we have the following data:
– A hash of the recording
– A matching hash of the possible match
– A song ID of the possible match
– The current time in our own recording
– The time of the hash in the possible match
Now we can substract the current time in our recording (for example, line 34) with the time of the hash-match (for example, line 1352). This difference is stored together with the song ID. Because this offset, this difference, tells us where we possibly could be in the song.
When we have gone through all the hashes from our recording we are left with a lot of song id’s and offsets. The cool thing is, if you have a lot of hashes with matching offsets, you’ve found your song.
The results
For example, when listening to The Kooks – Match Box for just 20 seconds, this is the output of my program:
01 |
Done loading: 2921 songs |
03 |
Start matching song... |
07 |
01: 08_the_kooks_-_match_box.mp3 with 16 matches. |
08 |
02: 04 Racoon - Smoothly.mp3 with 8 matches. |
09 |
03: 05 Röyksopp - Poor Leno.mp3 with 7 matches. |
10 |
04: 07_athlete_-_yesterday_threw_everyting_a_me.mp3 with 7 matches. |
11 |
05: Flogging Molly - WMH - Dont Let Me Dia Still Wonderin.mp3 with 7 matches. |
12 |
06: coldplay - 04 - sparks.mp3 with 7 matches. |
13 |
07: Coldplay - Help Is Round The Corner (yellow b-side).mp3 with 7 matches. |
14 |
08: the arcade fire - 09 - rebellion (lies).mp3 with 7 matches. |
15 |
09: 01-coldplay-_clocks.mp3 with 6 matches. |
16 |
10: 02 Scared Tonight.mp3 with 6 matches. |
17 |
11: 02-radiohead-pyramid_song-ksi.mp3 with 6 matches. |
18 |
12: 03 Shadows Fall.mp3 with 6 matches. |
19 |
13: 04 Röyksopp - In Space.mp3 with 6 matches. |
20 |
14: 04 Track04.mp3 with 6 matches. |
21 |
15: 05 - Dress Up In You.mp3 with 6 matches. |
22 |
16: 05 Supergrass - Can't Get Up.mp3 with 6 matches. |
23 |
17: 05 Track05.mp3 with 6 matches. |
24 |
18: 05The Fox In The Snow.mp3 with 6 matches. |
25 |
19: 05_athlete_-_wires.mp3 with 6 matches. |
26 |
20: 06 Racoon - Feel Like Flying.mp3 with 6 matches. |
30 |
Final prediction: 08_the_kooks_-_match_box.mp3.song with 16 matches. |
It works!!
Listening for 20 seconds it can match almost all the songs I have. And even this live recording of the Editors could be matched to the correct song after listening 40 seconds!
Again it feels like magic! :-)
Currently, the code isn’t in a releasable state and it doesn’t work perfectly. It has been a pure weekend-hack, more like a proof-of-concept / algorithm exploration.
Maybe, if enough people ask about it, I’ll clean it up and release it somewhere.
Update:
The Shazam patent holders lawyers are sending me emails to stop me from releasing the code and removing this blogpost, read the story here.
- Got error creating database manager: java.io.IOException解决方法
14/03/26 23:03:55 ERROR tool.BaseSqoopTool: Got error creating database manager: java.io.IOException ...
- ambari-server启动出现ERROR main] DBAccessorImpl:106 - Error while creating database accessor java.lang.ClassNotFoundException:com.mysql.jdbc.Driver问题解决办法(图文详解)
不多说,直接上干货! 问题详情 ambari-server启动时,报如下的错误 问题分析 注:启动ambari访问前,请确保mysql驱动已经放置在/usr/share/Java内且名字是mysql- ...
- Java性能提示(全)
http://www.onjava.com/pub/a/onjava/2001/05/30/optimization.htmlComparing the performance of LinkedLi ...
- java注释指导手册
译文出处: Toien Liu 原文出处:Dani Buiza 编者的话:注解是java的一个主要特性且每个java开发者都应该知道如何使用它. 我们已经在Java Code Geeks提供了丰富 ...
- Using OpenCV Java with Eclipse
转自:http://docs.opencv.org/trunk/doc/tutorials/introduction/java_eclipse/java_eclipse.html Using Open ...
- OFBIZ bug_ControlServlet.java:239:ERROR
错误日志: [java] 2014-09-23 00:11:34,877 (http-bio-0.0.0.0-8080-exec-4) [ ControlServlet.java:141:INFO ] ...
- Threads and Anonymous Classes in JAVA
As we all know,a thread is a separate process on your computer.you can run multiple threads all at t ...
- Using OpenCV Java with Eclipse(转)
转自:http://docs.opencv.org/trunk/doc/tutorials/introduction/java_eclipse/java_eclipse.html Using Open ...
- 【译】10. Java反射——数组
原文地址:http://tutorials.jenkov.com/java-reflection/arrays.html ======================================= ...
随机推荐
- Java基础知识强化之IO流笔记37:FileReader/FileWriter(转换流的子类)复制文本文件案例
1. 转换流的简化写法: 由于我们常见的操作都是使用本地默认编码,所以,不用指定编码.而转换流的名称有点长,所以,Java就提供了其子类供我们使用:FileReader / FileWriterOut ...
- 一个现代化的JSON库Moshi针对Android和Java
Moshi 是一个现代化的JSON库针对Android和Java.它可以很容易地解析JSON成Java对象: String json = ...; Moshi moshi = new Moshi.Bu ...
- 从键盘输入当月利润I,求应发放奖金总数?
企业发放的奖金根据利润提成.利润(I)低于或等于10万元时,奖金可提10%:利润高于10万元,低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%:20万到40万之间时 ...
- 服务器CPU使用率过高排查与解决思路
发现服务器的cpu使用率特别高 排查思路: -使用top或者mpstat查看cpu的使用情况# mpstat -P ALL 2 1Linux 2.6.32-358.el6.x86_64 (linux— ...
- ModelSim之命令行仿真入门
下面是我们的Tcl仿真步骤:启动ModelSim SE, 首先看到在在ModelSim SE右边的窗口有ModelSim> 这样的提示符.在提示符后,顺序运行以下命令: vlib work ...
- Linux SSh scp使用【远程文件/目录的传输】
一:Linux ssh scp的简介及作用: scp就是secure copy的简写,用于在linux下进行远程拷贝文件的命令,和它类似的命令有cp,不过cp只是在本机进行拷贝不能跨服务器. 有时我们 ...
- div置于页面底部
一直对于页面置底有一些困惑,下面这个例子不知道能不能解决 <!DOCTYPE html> <html lang="en"> <head> < ...
- bgycoding
//add by zzw@曾志伟 2015-12-9 [碧桂园项目] begin if(condition.indexOf("glbdef8 = 'Y'")>0){ Stri ...
- sublime中使用markdown
#为知笔记##为知笔记###为知笔记 1. 列表12. 列表23. 列表35. 顺序错了不用担心3. 写错的列表,会自动纠正 为知笔记---------------------- ```cpp int ...
- 20160329javaweb之JSP -session入门
3.Session Session 是一个域 !!作用范围:当前会话范围 !!生命周期: 当程序第一次调用到request.getSession()方法时说明客户端明确的需要用到session此时创建 ...