PageRenderTime 30ms CodeModel.GetById 18ms app.highlight 8ms RepoModel.GetById 1ms app.codeStats 0ms

/examples/quanta/quanta.py

http://echo-nest-remix.googlecode.com/
Python | 70 lines | 64 code | 1 blank | 5 comment | 1 complexity | 5cf47fe3ce719c161766efe21f3507a0 MD5 | raw file
 1#!/usr/bin/env python
 2# encoding: utf=8
 3
 4"""
 5quanta.py
 6
 7Insert silences between a song's segments, tatums, beats, or sections.
 8Demonstrates the Remix API's handling of audio quanta.
 9
10By Ben Lacker 2009-3-4.
11"""
12import sys
13
14import echonest.audio as audio
15
16usage = """
17Usage: 
18    python quanta.py <segments|tatums|beats|bars|sections> <inputfilename> <outputfilename> [e]
19
20Example:
21    python quanta.py beats SingleLadies.mp3 SingleLadiesBeats.mp3
22    
23The 'e' flag, inserts a silence equal in duration to the preceding audio quantum.
24Otherwise, each silence is one second long.
25"""
26
27ACCEPTED_UNITS = ["segments", "tatums", "beats", "bars", "sections"]
28
29def main(input_filename, output_filename, units, equal_silence):
30    audio_file = audio.LocalAudioFile(input_filename)
31    chunks = audio_file.analysis.__getattribute__(units)
32    num_channels = audio_file.numChannels
33    sample_rate = audio_file.sampleRate
34    if equal_silence:
35        new_shape = ((audio_file.data.shape[0] * 2) + 100000,
36                        audio_file.data.shape[1])
37    else:
38        new_shape = (audio_file.data.shape[0]+(len(chunks) * 44100) + 10000,
39                        audio_file.data.shape[1])
40    out = audio.AudioData(shape=new_shape, sampleRate=sample_rate,
41                            numChannels=num_channels)
42    for chunk in chunks:
43        chunk_data = audio_file[chunk]
44        if equal_silence:
45            silence_shape = chunk_data.data.shape
46        else:
47            silence_shape = (44100, chunk_data.data.shape[1])
48        silence = audio.AudioData(shape=silence_shape,
49                                sampleRate=sample_rate,
50                                numChannels=num_channels)
51        out.append(chunk_data)
52        out.append(silence)
53    out.encode(output_filename)
54
55if __name__ == '__main__':
56    try:
57        units = sys.argv[1]
58        input_filename = sys.argv[2]
59        output_filename = sys.argv[3]
60        if len(sys.argv) == 5:
61            equal_silence = True
62        else:
63            equal_silence = False
64    except:
65        print usage
66        sys.exit(-1)
67    if not units in ACCEPTED_UNITS:
68        print usage
69        sys.exit(-1)
70    main(input_filename, output_filename, units, equal_silence)