Пример #1
0
 def sonify_image(self):
     self.messageLabel.configure(text="")
     if self.targetImage is None:
         self.messageLabel.configure(text="Must load an image first.")
         return
     if self.targetImage.mode != 'RGB':
         self.messageLabel.configure(text='Not RGB.  %s is invalid.' %
                                     self.targetImage.mode)
         return
     self.messageLabel.configure(text="Converting ...")
     self.myParent.update_idletasks()
     imYCbCr = self.targetImage.convert(
         "YCbCr")  # Convert the image to YCbCr
     phi, rad, lum = sonify.phi_from_YCbCr(imYCbCr)
     amps = sonify.get_amplitudes(phi, figure=self.powerFigure)
     self.powerFigureCanvas.show()
     channels = ((sonify.super_sine_wave(freqs=sonify.TONES,
                                         amps=amps,
                                         framerate=self.rate), ), )
     self.samples = wavebender.compute_samples(channels,
                                               nsamples=self.rate *
                                               self.time)
     try:
         wavebender.write_wavefile('./temp.wav',
                                   samples=self.samples,
                                   nframes=self.rate * self.time,
                                   nchannels=1,
                                   framerate=self.rate)
         self.snd.read('./temp.wav')
         self.messageLabel.configure(text="Sonification complete.")
     except:
         self.messageLabel.configure(text="Errors in temp write.")
    def startPlaying(self, frequency=440.0, amplitude=0.5, framerate=48000, duration=60, bufsize=1024):

        if self.isWindows:
            while True:
                try:
                    import winsound
                    winsound.Beep(int(frequency), duration * 1000)
                except AttributeError:
                    pass
                if self.play == False:
                    break
        else:
            # create stream
            channels = ((wb.sine_wave(frequency, amplitude=amplitude, framerate=framerate),),)
            nframes = framerate * duration
            while self.play:
                try:
                    samples = wb.compute_samples(channels, nframes)
                    self.audioStream = MyStream(self.audioDev.open(format=self.audioDev.get_format_from_width(2), channels=1, rate=framerate, output=True))
                    wb.write_wavefile(self.audioStream, samples, nframes=nframes, sampwidth=2, framerate=framerate, bufsize=bufsize)
                except AttributeError:
                    pass
            else:
                self.audioStream.stopIt()
                self.audioDev.terminate()
            return
Пример #3
0
    def write_to_wav(self, name="wavegen-voice.wav", length=1, location="."):
        """Write the voice to a .wav file

        name: str
            The name of the file to be written
        location: path
            Where the file should be written to. Default is current working dir.
        """

        ext = ".wav"
        if name[: -len(ext)] != ext:
            name = str(name) + ".wav"

        # Generate a finite list of samples from our points generator
        no_of_samples = length * self.sample_rate
        self.samples = []

        for tick in range(no_of_samples):
            self.samples.append(self.points().next())

        self.normalise()
        channels = ((self.samples,) for i in range(self.channels))
        computed_samples = wb.compute_samples(channels, no_of_samples)

        wb.write_wavefile(
            name,
            samples=computed_samples,
            nframes=no_of_samples,
            nchannels=self.channels,
            sampwidth=2,
            framerate=self.sample_rate,
        )
Пример #4
0
def play_pitch(pitch, ms):
    frequency = pitch_to_frequency(pitch)

    num_channels = 1
    bit_rate = 16
    sample_rate = 44100
    volume = 1
    data_encoding = "signed"

    sox_output_type = "raw"

    channels = ((wavebender.sine_wave(frequency),),)
    samples = wavebender.compute_samples(channels, (sample_rate/1000) * ms )
    wavebender.write_pcm(open(tempfile.gettempdir() + "/pitch", 'w+'), samples, framerate=sample_rate)

    subprocess.call(["play", "-e", data_encoding, "-r", str(sample_rate), "-v", str(volume), "-t", sox_output_type, "-c", str(num_channels), "-b", str(bit_rate), "-"], stdin=open(tempfile.gettempdir() + "/pitch"))
Пример #5
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-r', '--rate', help="Sample rate in Hz", default=8000, type=int)
    parser.add_argument('-t', '--time', help="Duration of the wave in seconds.", default=4, type=int)
    parser.add_argument('-v', '--verbose', help="Print information to screen. Dont use if piping stdout to aplay!", action='store_true')
    parser.add_argument('-p', '--plot', help="Plot the power spectruem", action='store_true')
    parser.add_argument('-o', '--outfile', help="The .wav file to generate. Type '-' for stdout.", default=None, type=str)
    parser.add_argument('infile', help="The image file to read in. Type '-' to use test.jpg")
    args = parser.parse_args()
    
    if args.outfile == None:
        outfile = sys.stdout
    else:
        outfile = args.outfile

    # Open image file and read in the image.
    imOrig = Image.open(args.infile)
    if imOrig.mode != 'RGB':
        raise Exception('Not RGB.  %s is invalid.' % imOrig.mode)
    imR, imG, imB = imOrig.split()                     # Split into three images (one for each band).
    imYCbCr = imOrig.convert("YCbCr")                  # Convert the image to YCbCr
    imY, imCb, imCr = imYCbCr.split()                  # Split into three images (one for each band).

    if args.verbose:
        print_statistics(imOrig)
        print_statistics(imR)
        print_statistics(imG)
        print_statistics(imB)
        print_statistics(imYCbCr)
        print_statistics(imY)
        print_statistics(imCb)
        print_statistics(imCr)
        if args.plot:
            imY.show()
            imCb.show()
            imCr.show()
            plot_histogram(imY)
            plot_histogram(imCb)
            plot_histogram(imCr)

    phi, rad, lum = phi_from_YCbCr(imYCbCr)
    amps = get_amplitudes(phi, showPlot=args.plot)
    channels = ((super_sine_wave(freqs=TONES, amps=amps, framerate=args.rate),),)
    samples = wavebender.compute_samples(channels, nsamples=args.rate*args.time)
    wavebender.write_wavefile(outfile, samples=samples, nframes=(args.rate*args.time), nchannels=1, framerate=args.rate)
    def startPlaying(self,
                     frequency=440.0,
                     amplitude=0.5,
                     framerate=48000,
                     duration=60,
                     bufsize=1024):

        if self.isWindows:
            while True:
                try:
                    import winsound
                    winsound.Beep(int(frequency), duration * 1000)
                except AttributeError:
                    pass
                if self.play == False:
                    break
        else:
            # create stream
            channels = ((wb.sine_wave(frequency,
                                      amplitude=amplitude,
                                      framerate=framerate), ), )
            nframes = framerate * duration
            while self.play:
                try:
                    samples = wb.compute_samples(channels, nframes)
                    self.audioStream = MyStream(
                        self.audioDev.open(
                            format=self.audioDev.get_format_from_width(2),
                            channels=1,
                            rate=framerate,
                            output=True))
                    wb.write_wavefile(self.audioStream,
                                      samples,
                                      nframes=nframes,
                                      sampwidth=2,
                                      framerate=framerate,
                                      bufsize=bufsize)
                except AttributeError:
                    pass
            else:
                self.audioStream.stopIt()
                self.audioDev.terminate()
            return
Пример #7
0
 def write_wave(self):
     """Pull the output path from the write field 
     and save the sound wave to this file."""
     self.messageLabel.configure(text="")
     if self.channels is None:
         self.messageLabel.configure(text="Must sonify image first.")
         return
     filename = self.writeEntry.get()
     if filename is None:
         self.messageLabel.configure(text="Enter a filename to write.")
         return
     self.messageLabel.configure(text="Writing ...")
     self.myParent.update_idletasks()
     try:
         thisSamples = wavebender.compute_samples(self.channels, nsamples=self.rate*self.time)
         wavebender.write_wavefile(filename, samples=thisSamples, nframes=self.rate*self.time, 
                                   nchannels=1, framerate=self.rate)
         self.messageLabel.configure(text="Successfully written to %s" % filename)
     except:
         self.messageLabel.configure(text="Write failed. Try another image or output filename.")
Пример #8
0
 def sonify_image(self):
     self.messageLabel.configure(text="")
     if self.targetImage is None:
         self.messageLabel.configure(text="Must load an image first.")
         return
     if self.targetImage.mode != 'RGB':
         self.messageLabel.configure(text='Not RGB.  %s is invalid.' % self.targetImage.mode)
         return
     self.messageLabel.configure(text="Converting ...")
     self.myParent.update_idletasks()
     imYCbCr = self.targetImage.convert("YCbCr")                       # Convert the image to YCbCr
     phi, rad, lum = sonify.phi_from_YCbCr(imYCbCr)
     amps = sonify.get_amplitudes(phi, figure=self.powerFigure)
     self.powerFigureCanvas.show()
     channels = ((sonify.super_sine_wave(freqs=sonify.TONES, amps=amps, framerate=self.rate),),)
     self.samples = wavebender.compute_samples(channels, nsamples=self.rate*self.time)
     try:
         wavebender.write_wavefile('./temp.wav', samples=self.samples, nframes=self.rate*self.time, 
                           nchannels=1, framerate=self.rate)
         self.snd.read('./temp.wav')
         self.messageLabel.configure(text="Sonification complete.")
     except:
         self.messageLabel.configure(text="Errors in temp write.")
def create_wavefile(notes1,notes2, fileTime, wavefile, frameRate = 44100):
    '''Generates a wavefile given notes for channels 1 and 2'''
    
    # Build each channel

    channel1 = (notes1[:])   
    channel2 = (notes2[:])
    channels = (channel1,channel2)

    print "Channels constructed"
    print "Channels constructed"

    # Create a set of samples from these channels

    samples = compute_samples(channels, nsamples = fileTime*frameRate)

    print "Samples made: writing to wavefile ",wavefile
    print "This can take a while, please be patient!"

    # Writes the output to the .wav file
    write_wavefile(wavefile, samples)

    print "File ",wavefile, " written"
Пример #10
0
 def sound_write(self, frequency=440.0, duration=10.0, amplitude=0.1):
   square_wave = wavebender.square_wave(frequency, amplitude=amplitude);
   channels = ((square_wave,),)
   samples = wavebender.compute_samples(channels, 44100 * duration * 1)
   self._samples_write(samples, duration);
Пример #11
0
notes = {
	"a_flat"  : a_flat_5  ,
	"g"       : g_5       ,
	"f_sharp" : f_sharp_5 ,
	"f"       : f5        ,
	"e"       : e5        ,
	"e_flat"  : e_flat_5  ,
	"d"       : d5        ,
	"c_sharp" : c_sharp_5 ,
	"c"       : c5        ,
	"b"       : b4        ,
	"b_flat"  : b_flat_4  ,
	"a"       : a_4       ,
}

rate=44100
time=5.0
amplitude=0.3
samplewidth=2 # bytes

for freq in notes:

	channels = ((damped_wave(notes[freq], rate, amplitude),),)

	# convert the channel functions into waveforms
	samples = compute_samples(channels, rate * time)

	# write the samples to a file
	write_wavefile(freq + ".wav", samples, rate * time, len(channels), samplewidth, rate)
Пример #12
0
def generate_audio_src_stereo(filename, date):
    audio=audio_src(date)
    channels = ((audio_src(date), ), (audio_src(date), ) )
    samples = compute_samples(channels, None, )
    write_wavefile(filename, samples, None, 2, framerate=44100)
Пример #13
0
# Written 25/6/14 by dh4gan
# This script tests the wavebender package 
# Found at https://github.com/zacharydenton/wavebender

# This is my hack of the binaural.py example file

from wavebender import sine_wave, compute_samples, write_wavefile

channels = ((sine_wave(170.0, amplitude=0.1),),
            (sine_wave(178.0, amplitude=0.1),))

samples = compute_samples(channels)
write_wavefile("test.wav", samples)
Пример #14
0
#!/usr/bin/env python
import wavebender
from math import cos
import sys

f =open ("test.wav", 'wb');
square_wave = wavebender.square_wave(440.0, amplitude=0.1)
channels = ((square_wave,),)
duration = 2
samples = wavebender.compute_samples(channels, 44100 * duration * 1)
wavebender.write_wavefile(f, samples, 44100 * duration * 1, nchannels=1)
                                  b=-math.pi / 2))),
               a=1 / math.e), .5)
    b = exp(
        linear(sin(linear(x, a=.1 * 2 * math.pi, b=-10 * math.pi / 2)),
               a=.5,
               b=.5), .5)
    return a * b


# args = [2, .5, .5]

channels = ((super_sine_wave(frequency=100.0, amplitude=custom), ),
            (super_sine_wave(frequency=140.0, amplitude=custom), ))

duration = 25
samples = compute_samples(channels, duration * 44100)

write_wavefile('100-140 pulse original equation.wav', samples)

# freqs = [20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140]
#
# oscs = [1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]
# for freq in freqs:
#     for osc in oscs:
#         amp = [math.sin, osc * 2 * math.pi, -math.pi/2, .5, .5]
#         channels = ((sine_wave(frequency = freq, amplitude=amp),),
#                     (sine_wave(frequency = freq, amplitude=amp),))
#         samples = compute_samples(channels, duration * 44100)
#         write_wavefile('/Users/kaandonbekci/dev/pervasivetech/Room/audiotory/audio/test/abi{}Hz_{}osc.wav'.format(freq, osc),samples)
#         print('finished {}Hz and {}osc.'.format(freq, osc))
Пример #16
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-r',
                        '--rate',
                        help="Sample rate in Hz",
                        default=8000,
                        type=int)
    parser.add_argument('-t',
                        '--time',
                        help="Duration of the wave in seconds.",
                        default=4,
                        type=int)
    parser.add_argument(
        '-v',
        '--verbose',
        help="Print information to screen. Dont use if piping stdout to aplay!",
        action='store_true')
    parser.add_argument('-p',
                        '--plot',
                        help="Plot the power spectruem",
                        action='store_true')
    parser.add_argument('-o',
                        '--outfile',
                        help="The .wav file to generate. Type '-' for stdout.",
                        default=None,
                        type=str)
    parser.add_argument(
        'infile', help="The image file to read in. Type '-' to use test.jpg")
    args = parser.parse_args()

    if args.outfile == None:
        outfile = sys.stdout
    else:
        outfile = args.outfile

    # Open image file and read in the image.
    imOrig = Image.open(args.infile)
    if imOrig.mode != 'RGB':
        raise Exception('Not RGB.  %s is invalid.' % imOrig.mode)
    imR, imG, imB = imOrig.split(
    )  # Split into three images (one for each band).
    imYCbCr = imOrig.convert("YCbCr")  # Convert the image to YCbCr
    imY, imCb, imCr = imYCbCr.split(
    )  # Split into three images (one for each band).

    if args.verbose:
        print_statistics(imOrig)
        print_statistics(imR)
        print_statistics(imG)
        print_statistics(imB)
        print_statistics(imYCbCr)
        print_statistics(imY)
        print_statistics(imCb)
        print_statistics(imCr)
        if args.plot:
            imY.show()
            imCb.show()
            imCr.show()
            plot_histogram(imY)
            plot_histogram(imCb)
            plot_histogram(imCr)

    phi, rad, lum = phi_from_YCbCr(imYCbCr)
    amps = get_amplitudes(phi, showPlot=args.plot)
    channels = ((super_sine_wave(freqs=TONES, amps=amps,
                                 framerate=args.rate), ), )
    samples = wavebender.compute_samples(channels,
                                         nsamples=args.rate * args.time)
    wavebender.write_wavefile(outfile,
                              samples=samples,
                              nframes=(args.rate * args.time),
                              nchannels=1,
                              framerate=args.rate)