Пример #1
0
 def load_wav(self, wavpath, pitchpath):
     src = WaveReader(wavpath)
     fp = open(pitchpath)
     for line in fp:
         line = line.strip()
         if not line:
             print
         (line,_,_) = line.partition('#')
         if not line: continue
         (f, _, pitch) = line.partition(' ')
         f = int(f)
         pitch = int(pitch)
         src.seek(f)
         r = []
         (nframes, data) = src.readraw(int(src.framerate/pitch))
         for (name,pat) in self.pats:
             s = wavcorr.matchs16(pat, 0, nframes, data)
             if self.threshold <= s:
                 r.append((s, name))
         if r:
             r.sort(reverse=True)
             print f, ' '.join( '%.04f:%s' % (s,name) for (s,name) in r )
     fp.close()
     src.close()
     return
Пример #2
0
 def load_wav(self, wavpath, pitchpath):
     src = WaveReader(wavpath)
     fp = open(pitchpath)
     for line in fp:
         line = line.strip()
         if not line:
             print
         (line, _, _) = line.partition('#')
         if not line: continue
         (f, _, pitch) = line.partition(' ')
         f = int(f)
         pitch = int(pitch)
         src.seek(f)
         r = []
         (nframes, data) = src.readraw(int(src.framerate / pitch))
         for (name, pat) in self.pats:
             s = wavcorr.matchs16(pat, 0, nframes, data)
             if self.threshold <= s:
                 r.append((s, name))
         if r:
             r.sort(reverse=True)
             print f, ' '.join('%.04f:%s' % (s, name) for (s, name) in r)
     fp.close()
     src.close()
     return
Пример #3
0
def main(argv):
    import getopt
    def usage():
        print 'usage: %s [-v] [-o out.wav] [-t f0-f1] wav ...' % argv[0]
        return 100
    def getv(v):
        if '.' in v:
            return float(v)
        else:
            return int(v)
    try:
        (opts, args) = getopt.getopt(argv[1:], 'vo:t:')
    except getopt.GetoptError:
        return usage()
    verbose = 0
    outfp = None
    ranges = []
    for (k, v) in opts:
        if k == '-v': verbose += 1
        elif k == '-o': outfp = open(v, 'wb')
        elif k == '-t':
            (f0,_,f1) = v.partition('-')
            ranges.append((getv(f0), getv(f1)))
    dst = None
    for path in args:
        src = WaveReader(path)
        if verbose:
            print >>sys.stderr, \
                ('%s: nchannels=%r, sampwidth=%r, framerate=%r, nframes=%r' %
                 (path, src.nchannels, src.sampwidth, src.framerate, src.nframes))
        if dst is None:
            if outfp is None:
                dst = WavePlayer(nchannels=src.nchannels,
                                 sampwidth=src.sampwidth,
                                 framerate=src.framerate)
            else:
                dst = WaveWriter(outfp,
                                 nchannels=src.nchannels,
                                 sampwidth=src.sampwidth,
                                 framerate=src.framerate)
        for (f0,f1) in ranges:
            if isinstance(f0, float):
                f0 = int(f0*src.framerate)
            if isinstance(f1, float):
                f1 = int(f1*src.framerate)
            src.seek(f0)
            if f1 < f0:
                f1 = src.nframes
            (_,buf) = src.readraw(f1-f0)
            dst.writeraw(buf)
        src.close()
    if dst is not None:
        dst.close()
    if outfp is not None:
        outfp.close()
    return
Пример #4
0
def fradosify(path, outfp, delta):
    print >>sys.stderr, 'reading: %r' % path
    ratio = pow(2, delta/12.0)
    src = WaveReader(path)
    if src.nchannels != 1: raise ValueError('invalid number of channels')
    if src.sampwidth != 2: raise ValueError('invalid sampling width')
    dst = WaveWriter(outfp, framerate=src.framerate)
        
    contour = PitchContour(src.framerate)
    contour.load(src)
    def f(t):
        x = contour.getavg(t)
        if x is not None:
            x = int(x*ratio)
        return x
    src.seek(0)
    dst.write(psola(src.read(), src.framerate, contour.getsrc, f, contour.wmin))
    
    src.close()
    dst.close()
    return
Пример #5
0
def main(argv):
    import getopt
    from wavestream import WaveReader

    def usage():
        print(
            'usage: %s [-d] [-M|-F] [-n pitchmin] [-m pitchmax]'
            ' [-T threshold_sim] [-S threshold_mag] wav ...' % argv[0])
        return 100

    def parse_range(x):
        (b, _, e) = x.partition('-')
        try:
            b = int(b)
        except ValueError:
            b = 0
        try:
            e = int(e)
        except ValueError:
            e = 0
        return (b, e)

    try:
        (opts, args) = getopt.getopt(argv[1:], 'dMFn:m:T:S:')
    except getopt.GetoptError:
        return usage()
    debug = 0
    pitchmin = 70
    pitchmax = 400
    threshold_sim = 0.75
    threshold_mag = 0.025
    bufsize = 10000
    for (k, v) in opts:
        if k == '-d': debug += 1
        elif k == '-M': (pitchmin, pitchmax) = (75, 200)  # male voice
        elif k == '-F': (pitchmin, pitchmax) = (150, 300)  # female voice
        elif k == '-n': pitchmin = int(v)
        elif k == '-m': pitchmax = int(v)
        elif k == '-T': threshold_sim = float(v)
        elif k == '-S': threshold_mag = float(v)
    detector = None
    smoother = None
    for arg1 in args:
        (path, _, ranges) = arg1.partition(':')
        ranges = [parse_range(x) for x in ranges.split(',') if x]
        if not ranges:
            ranges.append((0, 0))
        print '#', path, ranges
        src = WaveReader(path)
        if src.nchannels != 1: raise ValueError('invalid number of channels')
        if src.sampwidth != 2: raise ValueError('invalid sampling width')
        framerate = src.framerate
        if detector is None:
            detector = PitchDetector(wmin=framerate / pitchmax,
                                     wmax=framerate / pitchmin,
                                     threshold_sim=threshold_sim)
            smoother = PitchSmoother(2 * framerate / pitchmin,
                                     threshold_sim=threshold_sim,
                                     threshold_mag=threshold_mag)
        for (b, e) in ranges:
            if e == 0:
                e = src.nframes
            src.seek(b)
            length = e - b
            i0 = b
            while length:
                (nframes, buf) = src.readraw(min(bufsize, length))
                if not nframes: break
                length -= nframes
                seq = detector.feed(buf, nframes)
                for (n0, pitches, data) in seq:
                    if debug:
                        print('# %d: %r' % (n0, pitches))
                    for streak in smoother.feed(i0, n0, pitches):
                        for (i1, n1, spitches) in streak:
                            print i1, n1, ' '.join('%d:%.4f' % (w, sim)
                                                   for (_, w, sim) in spitches)
                        print
                    i0 += n0
        src.close()
    return
Пример #6
0
class WavEd(object):
    def __init__(self):
        self._wav = None
        self._cur = None
        self._curs = {}
        self._player = None
        return

    def stop(self):
        if self._player is not None:
            self._player.stop()
            self._player = None
        return

    def close(self):
        self.stop()
        if self._wav is not None:
            self._wav.close()
            self._wav = None
            self._cur = None
            self._curs = {}
        return

    def read(self, path):
        self.close()
        self._wav = WaveReader(path)
        self._cur = WavCursor(self._wav)
        self._cur.set_length('1.0')
        self._curs = {}
        print('Read: rate=%d, frames=%d, duration=%.3f' %
              (self._wav.framerate, self._wav.nframes,
               self._wav.nframes / float(self._wav.framerate)))
        return

    def write(self, cur, path, force=False):
        if not force and os.path.exists(path):
            raise WavEdError('File exists: %r' % path)
        nframes = cur.get_length()
        fp = open(path, 'wb')
        writer = WaveWriter(fp,
                            nchannels=self._wav.nchannels,
                            sampwidth=self._wav.sampwidth,
                            framerate=self._wav.framerate)
        self._wav.seek(cur.start)
        (_, data) = self._wav.readraw(nframes)
        writer.writeraw(data)
        writer.close()
        fp.close()
        print('Written: %r, rate=%d, frames=%d, duration=%.3f' %
              (path, writer.framerate, nframes,
               nframes / float(writer.framerate)))
        return

    def play(self, cur):
        nframes = cur.get_length()
        self.stop()
        self._player = WavePlayer(nchannels=self._wav.nchannels,
                                  sampwidth=self._wav.sampwidth,
                                  framerate=self._wav.framerate)
        self._wav.seek(cur.start)
        (_, data) = self._wav.readraw(nframes)
        self._player.writeraw(data)
        self._player.flush()
        return

    def show(self, cur):
        print cur
        return

    def run(self):
        self.exec_command('p')
        while 1:
            try:
                s = raw_input('> ')
                self.stop()
                s = s.strip()
                if s:
                    self.exec_command(s)
            except (EOFError, WavEdExit):
                break
        return

    def show_help(self):
        print 'commands: q)uit, r)ead, w)rite, p)lay, s)tart, e)nd, l)ength'
        print '          C)reate, D)elete, R)ename, J)ump, L)ist, load, save, export'
        return

    def exec_command(self, s):
        try:
            if s[0].isdigit() or s[0] in '+-':
                self.cmd_s(s)
                return

            (c, _, v) = s.partition(' ')
            c = 'cmd_' + c.replace('!', '_f')
            if hasattr(self, c):
                getattr(self, c)(v)
            else:
                self.show_help()
        except WavEdExit, e:
            raise
        except WavNoFileError, e:
            print 'no file'
Пример #7
0
class WavEd(object):

    def __init__(self):
        self._wav = None
        self._cur = None
        self._curs = {}
        self._player = None
        return

    def stop(self):
        if self._player is not None:
            self._player.stop()
            self._player = None
        return

    def close(self):
        self.stop()
        if self._wav is not None:
            self._wav.close()
            self._wav = None
            self._cur = None
            self._curs = {}
        return

    def read(self, path):
        self.close()
        self._wav = WaveReader(path)
        self._cur = WavCursor(self._wav)
        self._cur.set_length('1.0')
        self._curs = {}
        print ('Read: rate=%d, frames=%d, duration=%.3f' %
               (self._wav.framerate, self._wav.nframes,
                self._wav.nframes/float(self._wav.framerate)))
        return

    def write(self, cur, path, force=False):
        if not force and os.path.exists(path):
            raise WavEdError('File exists: %r' % path)
        nframes = cur.get_length()
        fp = open(path, 'wb')
        writer = WaveWriter(fp,
                            nchannels=self._wav.nchannels,
                            sampwidth=self._wav.sampwidth,
                            framerate=self._wav.framerate)
        self._wav.seek(cur.start)
        (_,data) = self._wav.readraw(nframes)
        writer.writeraw(data)
        writer.close()
        fp.close()
        print ('Written: %r, rate=%d, frames=%d, duration=%.3f' %
               (path, writer.framerate, nframes,
                nframes/float(writer.framerate)))
        return

    def play(self, cur):
        nframes = cur.get_length()
        self.stop()
        self._player = WavePlayer(nchannels=self._wav.nchannels,
                                  sampwidth=self._wav.sampwidth,
                                  framerate=self._wav.framerate)
        self._wav.seek(cur.start)
        (_,data) = self._wav.readraw(nframes)
        self._player.writeraw(data)
        self._player.flush()
        return

    def show(self, cur):
        print cur
        return

    def run(self):
        self.exec_command('p')
        while 1:
            try:
                s = raw_input('> ')
                self.stop()
                s = s.strip()
                if s:
                    self.exec_command(s)
            except (EOFError, WavEdExit):
                break
        return

    def show_help(self):
        print 'commands: q)uit, r)ead, w)rite, p)lay, s)tart, e)nd, l)ength'
        print '          C)reate, D)elete, R)ename, J)ump, L)ist, load, save, export'
        return
    
    def exec_command(self, s):
        try:
            if s[0].isdigit() or s[0] in '+-':
                self.cmd_s(s)
                return

            (c,_,v) = s.partition(' ')
            c = 'cmd_'+c.replace('!','_f')
            if hasattr(self, c):
                getattr(self, c)(v)
            else:
                self.show_help()
        except WavEdExit, e:
            raise
        except WavNoFileError, e:
            print 'no file'