Ejemplo n.º 1
0
def slow_down_sound(sound, rate):
    """  returns a sound which is a slowed down version of the original.
           rate - at which the sound should be slowed down.  eg. 0.5 would be half speed.
    """

    raise NotImplementedError()
    grow_rate = 1 / rate

    # make it 1/rate times longer.

    a1 = sndarray.array(sound)

    surf = pygame.surfarray.make_surface(a1)
    print(a1.shape[0] * grow_rate)
    scaled_surf = pygame.transform.scale(
        surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
    print(scaled_surf)
    print(surf)

    a2 = a1 * rate
    print(a1.shape)
    print(a2.shape)
    print(a2)
    sound2 = sndarray.make_sound(a2.astype(int16))
    return sound2
Ejemplo n.º 2
0
def load_song(fname):
    ff = open('%s/%s.pkl' % (ddir, fname),'w')

    mixer.init(f*multiplier)
    s_full = mixer.Sound('%s/%s' % (mdir, fname))
    a_full = snd.array(s_full)

    pickle.dump(a_full,ff)
    ff.close()
Ejemplo n.º 3
0
def load_song(fname):
    ff = open('%s/%s.pkl' % (ddir, fname), 'w')

    mixer.init(f * multiplier)
    s_full = mixer.Sound('%s/%s' % (mdir, fname))
    a_full = snd.array(s_full)

    pickle.dump(a_full, ff)
    ff.close()
Ejemplo n.º 4
0
def make_echo(sound, samples_per_second,  mydebug = True):
    """ returns a sound which is echoed of the last one.
    """

    echo_length = 3.5

    a1 = sndarray.array(sound)
    if mydebug:
        print ('SHAPE1: %s' % (a1.shape,))

    length = a1.shape[0]

    #myarr = zeros(length+12000)
    myarr = zeros(a1.shape, int32)

    if len(a1.shape) > 1:
        mult = a1.shape[1]
        size = (a1.shape[0] + int(echo_length * a1.shape[0]), a1.shape[1])
        #size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)), a1.shape[1])
    else:
        mult = 1
        size = (a1.shape[0] + int(echo_length * a1.shape[0]),)
        #size = (a1.shape[0] + int(a1.shape[0] + (echo_length * 3000)),)

    if mydebug:
        print (int(echo_length * a1.shape[0]))
    myarr = zeros(size, int32)



    if mydebug:
        print ("size %s" % (size,))
        print (myarr.shape)
    myarr[:length] = a1
    #print (myarr[3000:length+3000])
    #print (a1 >> 1)
    #print ("a1.shape %s" % (a1.shape,))
    #c = myarr[3000:length+(3000*mult)]
    #print ("c.shape %s" % (c.shape,))

    incr = int(samples_per_second / echo_length)
    gap = length


    myarr[incr:gap+incr] += a1>>1
    myarr[incr*2:gap+(incr*2)] += a1>>2
    myarr[incr*3:gap+(incr*3)] += a1>>3
    myarr[incr*4:gap+(incr*4)] += a1>>4

    if mydebug:
        print ('SHAPE2: %s' % (myarr.shape,))


    sound2 = sndarray.make_sound(myarr.astype(int16))

    return sound2
Ejemplo n.º 5
0
    def generateNotes(self):
        self.parent.write("Generating notes...")
        for i in range(-36,60):
            for key in self.key:
                if i in key:
                    if not os.path.exists(self.basicNote[:-4] + os.path.sep +
                        str(i) + '.wav'):
                        factor = 2**(1.0 * i / 12.0)
                        if self.lengthAdjusted:
                            (samplerate,smp)=paulstretch.load_wav(
                                self.basicNote)
                            paulstretch.paulstretch(samplerate, smp, factor,
                                self.windowSize,
                                self.basicNote[:-4]+"temp"+".wav")
                            note = pgm.Sound(self.basicNote[:-4]+"temp"+".wav")
                        else:
                            note = pgm.Sound(self.basicNote)

                        note.set_volume(0)
                        note.play()
                        basicNoteArray = pgsa.array(note)
                        basicNoteResampled = []
                        for ch in range(basicNoteArray.shape[1]):
                            sound_channel = basicNoteArray[:,ch]
                            basicNoteResampled.append(np.array(
                                self.speedx(sound_channel, factor)))

                        basicNoteResampled = np.transpose(np.array(
                            basicNoteResampled)).copy(order='C')
                        noteOut = pgsa.make_sound(basicNoteResampled.astype(
                            basicNoteArray.dtype))
                        noteFile = wave.open(self.basicNote[:-4] + os.path.sep +
                            str(i) + '.wav', 'w')
                        noteFile.setframerate(44100)
                        noteFile.setnchannels(2)
                        noteFile.setsampwidth(2)
                        noteFile.writeframesraw(noteOut.get_raw())
                        noteFile.close()
                        self.parent.write(self.parent.notes[
                            i%len(self.parent.notes)] + "(" +
                            str(i//len(self.parent.notes)+5) + ") Generated!")

        if os.path.exists(self.basicNote[:-4]+"temp"+".wav"):
            os.remove(self.basicNote[:-4]+"temp"+".wav")
Ejemplo n.º 6
0
def slow_down_sound(sound, rate):
    """  returns a sound which is a slowed down version of the original.
           rate - at which the sound should be slowed down.  eg. 0.5 would be half speed.
    """

    raise NotImplementedError()
    grow_rate = 1 / rate

    # make it 1/rate times longer.

    a1 = sndarray.array(sound)

    surf = pygame.surfarray.make_surface(a1)
    print (a1.shape[0] * grow_rate)
    scaled_surf = pygame.transform.scale(surf, (int(a1.shape[0] * grow_rate), a1.shape[1]))
    print (scaled_surf)
    print (surf)

    a2 = a1 * rate
    print (a1.shape)
    print (a2.shape)
    print (a2)
    sound2 = sndarray.make_sound(a2.astype(int16))
    return sound2
Ejemplo n.º 7
0
    def initSong(self, infoFile):
        print('Loading Info.json : ', infoFile)
        self.loadInfoJson(infoFile)

        self.data, self.samplerate = soundfile.read(self.songPath + '/' +
                                                    self.audioFile)
        self.beatsPerBar = 4
        MX.quit()
        self.mixer = MX

        print('Sample rate: ', self.samplerate)

        self.mixer.pre_init(self.samplerate, -16, 2, 2048)
        self.mixer.init(self.samplerate)
        self.sound = self.mixer.Sound(self.songPath + '/' + self.audioFile)
        self.lengthInSeconds = self.sound.get_length()
        self.lengthInBeats = 1000  #DEBUG self.secToBeat(self.lengthInSeconds)
        self.pos = 0
        self.music = self.mixer.music.load(self.songPath + '/' +
                                           self.audioFile)

        self.spectrogramExist = self.isSpectrogramMade()
        if not self.spectrogramExist:
            print('getting samples')
            samples = SA.array(self.sound)
            print('average stereo')
            fade = []
            for sample in samples:
                fade.append((int(sample[0]) + int(sample[1])) / 2.0)
            fade = numpy.asarray(fade)
            print('fft')
            f, t, Sxx = signal.spectrogram(fade, 48000, nperseg=256, nfft=2048)

            print('coloring')
            data = []
            colormax = 255
            map = []
            j = colorscale = 256
            k = j / 2
            for i in range(colorscale):
                red = colormax - (i / colorscale * colormax)
                if i < k:
                    green = (i / colorscale * colormax)
                else:
                    green = (j / colorscale * colormax)
                blue = (i / colorscale * colormax)
                j -= 1
                alpha = 100
                map.append((int(blue), int(red), int(green), alpha))
            j = 255
            while j > 0:
                j -= 15
                map.append((0, 0, j))
            for s in Sxx:
                for d in (s.tolist()):
                    if d > 4000:
                        data.append(map[0])
                    elif d == 0:
                        data.append(map[-1])
                    else:
                        data.append(map[int((len(map) -
                                             (d / 4000 * len(map))) - 1)])
            print('Creating Pixmap')
            im = Image.new('RGBA', (len(t), len(f)))
            im.putdata(data)
            im.save(spectrogram_dir + self.audioFile + '.png')
Ejemplo n.º 8
0
if __name__ == '__main__':

    main_dir = os.path.split(os.path.abspath(__file__))[0]

    pygame.init()
    mix = pygame.mixer.get_init()
    sound = mixer.Sound(os.path.join(main_dir, '', 'pulse.ogg'))

    while mixer.get_busy():
        pygame.time.wait(200)

    sound.play()

    while mixer.get_busy():
        pygame.time.wait(200)

    array = sndarray.array(sound).astype(dtype=numpy.int16)
    sound2 = make_echo(array_=array, mixer_samples_rate_=mix[0])

    sound2.play()

    while mixer.get_busy():
        pygame.time.wait(200)

    # print(timeit.timeit('make_echo(array, mix[0])', 'from __main__ import make_echo, array, mix', number=100) / 100)
    plt.plot(array)
    plt.show()
    plt.plot(pygame.sndarray.samples(sound2))
    plt.show()