source: python/aubio/gnuplot.py @ 9bb8151

feature/autosinkfeature/cnnfeature/cnn_orgfeature/constantqfeature/crepefeature/crepe_orgfeature/pitchshiftfeature/pydocstringsfeature/timestretchfix/ffmpeg5pitchshiftsamplertimestretchyinfft+
Last change on this file since 9bb8151 was 9bb8151, checked in by Paul Brossier <piem@altern.org>, 18 years ago

use gnuplot_create in plot_audio
use gnuplot_create in plot_audio

  • Property mode set to 100644
File size: 6.2 KB
Line 
1"""Copyright (C) 2004 Paul Brossier <piem@altern.org>
2print aubio.__LICENSE__ for the terms of use
3"""
4
5__LICENSE__ = """\
6         Copyright (C) 2004 Paul Brossier <piem@altern.org>
7
8         This program is free software; you can redistribute it and/or modify
9         it under the terms of the GNU General Public License as published by
10         the Free Software Foundation; either version 2 of the License, or
11         (at your option) any later version.
12
13         This program is distributed in the hope that it will be useful,
14         but WITHOUT ANY WARRANTY; without even the implied warranty of
15         MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16         GNU General Public License for more details.
17
18         You should have received a copy of the GNU General Public License
19         along with this program; if not, write to the Free Software
20         Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
21"""
22
23
24__notesheight = 0.25
25
26
27def audio_to_array(filename):
28        import aubio.aubioclass
29        import numarray
30        hopsize  = 2048
31        filei    = aubio.aubioclass.sndfile(filename)
32        framestep = 1/(filei.samplerate()+0.)
33        channels = filei.channels()
34        myvec    = aubio.aubioclass.fvec(hopsize,channels)
35        data = []
36        readsize = hopsize
37        while (readsize==hopsize):
38                readsize = filei.read(hopsize,myvec)
39                #for i in range(channels):
40                i = 0
41                curpos = 0
42                while (curpos < readsize):
43                        data.append(myvec.get(curpos,i))
44                        curpos+=1
45        time = numarray.arange(len(data))*framestep
46        return time,data
47
48def plot_audio(filenames, outplot='', extension='', start=0, end=None, noaxis=None,xsize=1.,ysize=1.):
49        g = gnuplot_create(outplot, extension)
50        d = []
51        todraw = len(filenames)
52        xorig = 0.
53        xratio = 1./todraw
54        g.gnuplot('set size %f,%f;' % (xsize,ysize) )
55        g.gnuplot('set multiplot;')
56        while (len(filenames)):
57                time,data = audio_to_array(filenames.pop(0))
58                if not noaxis and todraw==1:
59                        if max(time) < 1.:
60                                time = [t*1000. for t in time]
61                                g.xlabel('Time (ms)')
62                        else:
63                                g.xlabel('Time (s)')
64                        g.ylabel('Amplitude')
65                d.append(make_audio_plot(time,data))
66                g.gnuplot('set size %f,%f;' % (xsize*xratio,ysize) )
67                g.gnuplot('set origin %f,0.;' % (xorig) )
68                g.gnuplot('set style data lines; \
69                        set yrange [-1.:1.]; \
70                        set xrange [0:%f]' % time[-1]) 
71                g.plot(d.pop(0))
72                xorig += xsize*xratio
73        g.gnuplot('unset multiplot;')
74
75def audio_to_spec(filename,minf = 0, maxf = 0, lowthres = -20., 
76                bufsize= 8192, hopsize = 1024):
77        from aubioclass import fvec,cvec,pvoc,sndfile
78        from math import log10
79        filei     = sndfile(filename)
80        srate     = float(filei.samplerate())
81        framestep = hopsize/srate
82        freqstep  = srate/bufsize
83        channels  = filei.channels()
84        myvec = fvec(hopsize,channels)
85        myfft = cvec(bufsize,channels)
86        pv    = pvoc(bufsize,hopsize,channels)
87        data,time,freq = [],[],[]
88
89        if maxf == 0.: maxf = bufsize/2
90        else: maxf = int(maxf/freqstep)
91        if minf: minf = int(minf/freqstep)
92        else: minf = 0 
93
94        for f in range(minf,maxf):
95                freq.append(f*freqstep)
96        readsize = hopsize
97        frameread = 0
98        while (readsize==hopsize):
99                readsize = filei.read(hopsize,myvec)
100                pv.do(myvec,myfft)
101                frame = []
102                i = 0 #for i in range(channels):
103                curpos = minf
104                while (curpos < maxf):
105                        frame.append(max(lowthres,20.*log10(myfft.get(curpos,i)**2+0.00001)))
106                        curpos+=1
107                time.append(frameread*framestep)
108                data.append(frame)
109                frameread += 1
110        # crop data if unfinished frames
111        if len(data[-1]) != len(data[0]):
112                data = data[0:-2]
113                time = time[0:-2]
114        # verify size consistency
115        assert len(data) == len(time)
116        assert len(data[0]) == len(freq)
117        return data,time,freq
118
119def plot_spec(filename, outplot='',extension='', fileout=None, start=0, end=None, noaxis=None,log=1, minf=0, maxf= 0, xsize = 1., ysize = 1.,bufsize=8192, hopsize=1024):
120        import Gnuplot
121        g = gnuplot_create(outplot,extension)
122        data,time,freq = audio_to_spec(filename,minf=minf,maxf=maxf,bufsize=bufsize,hopsize=hopsize)
123        xorig = 0.
124        if not noaxis:
125                if max(time) < 1.:
126                        time = [t*1000. for t in time]
127                        g.xlabel('Time (ms)')
128                else:
129                        g.xlabel('Time (s)')
130                g.ylabel('Frequency (Hz)')
131        g('set size %f,%f' % (xsize, ysize))
132        g('set pm3d map')
133        g('set palette rgbformulae -25,-24,-32')
134        #g('set colorbox horizontal')
135        g('set xrange [0.:%f]' % time[-1]) 
136        g('set yrange [%f:%f]' % (minf,maxf))
137        if log:
138                g('set yrange [%f:%f]' % (max(10,minf),maxf))
139                g('set log y')
140        g.splot(Gnuplot.GridData(data,time,freq, binary=1))
141        #xorig += 1./todraw
142
143def downsample_audio(time,data,maxpoints=10000):
144        """ resample audio data to last only maxpoints """
145        import numarray
146        length = len(time)
147        downsample = length/maxpoints
148        if downsample == 0: downsample = 1
149        x = numarray.array(time).resize(length)[0:-1:downsample]
150        y = numarray.array(data).resize(length)[0:-1:downsample]
151        return x,y
152
153def make_audio_plot(time,data,maxpoints=10000):
154        """ create gnuplot plot from an audio file """
155        import numarray
156        import Gnuplot, Gnuplot.funcutils
157        length = len(time)
158        downsample = length/maxpoints
159        if downsample == 0: downsample = 1
160        x = numarray.array(time).resize(length)[0:-1:downsample]
161        y = numarray.array(data).resize(length)[0:-1:downsample]
162        return Gnuplot.Data(x,y,with='lines')
163
164def gnuplot_init(outplot,debug=0,persist=1):
165        # prepare the plot
166        import Gnuplot
167        g = Gnuplot.Gnuplot(debug=debug, persist=persist)
168        if outplot == 'stdout':
169                g("set terminal png fontfile 'p052023l.pfb'")
170                #g('set output \'%s\'' % outplot)
171        elif outplot:
172                extension = outplot.split('.')[-1]
173                if extension == 'ps': extension = 'postscript'
174                g('set terminal %s' % extension)
175                g('set output \'%s\'' % outplot)
176        return g
177
178def gnuplot_create(outplot='',extension='',debug=0,persist=1):
179        import Gnuplot
180        g = Gnuplot.Gnuplot(debug=debug, persist=persist)
181        if not extension or not outplot: return g
182        if   extension == 'ps':  ext, extension = '.ps' , 'postscript'
183        elif extension == 'eps': ext, extension = '.eps' , 'postscript enhanced'
184        elif extension == 'epsc': ext, extension = '.eps' , 'postscript enhanced color'
185        elif extension == 'png': ext, extension = '.png', 'png'
186        elif extension == 'svg': ext, extension = '.svg', 'svg'
187        else: exit("ERR: unknown plot extension")
188        g('set terminal %s' % extension)
189        if outplot != "stdout":
190                g('set output \'%s%s\'' % (outplot,ext))
191        return g
Note: See TracBrowser for help on using the repository browser.