Example #1
0
 def test_Save(self):
     cidx = self._sample_1.extract_channel(0)
     channel = self._sample_1.get_channel(cidx)
     audio = Audio()
     audio.append_channel( channel )
     signals.save( TestChannel._sample_path_new, audio )
     savedaudio = signals.open(TestChannel._sample_path_new)
     
     self._sample_1.rewind()
     frames = self._sample_1.read_frames( self._sample_1.get_nframes() )
     savedframes = savedaudio.read_frames( self._sample_1.get_nframes() )
     self.assertEqual(len(frames), len(savedframes))
     self.assertEqual(frames, savedframes)
Example #2
0
    def export(self, inputname, outputname):
        """
        Create a new wav file with requested parameters.

        @param inputname (string) name of the inputfile
        @param reqSamplewidth (string) name of the outputfile

        """
        toconvert = False

        audio = signals.open(inputname)

        if (audio.get_sampwidth() < self._reqSamplewidth):
            raise NameError("The sample width of ("+str(audio.get_sampwidth())+") of the given file is not appropriate. " + str(self._reqSamplewidth) + " bytes required")

        if (audio.get_framerate() < self._reqFramerate):
            raise NameError("The framerate of ("+str(audio.get_framerate())+") of the given file is not appropriate. " + str(self._reqFramerate) + " Hz required")

        if (self._reqSamplewidth != audio.get_sampwidth()):
            toconvert = True
            if self._logfile:
                self._logfile.print_message("The sample width of ("+str(audio.get_sampwidth())+") of the given file is not appropriate. Sample width is changed to " + str(self._reqSamplewidth) + " bytes", indent=3, status=1)

        if (self._reqChannels != audio.get_nchannels()):
            toconvert = True
            if self._logfile:
                self._logfile.print_message("The number of channels of ("+str(audio.get_nchannels())+") of the given file is not appropriate. Number of channels is changed to " + str(self._reqChannels) + " channels", indent=3, status=1)

        if (self._reqFramerate != audio.get_framerate()):
            toconvert = True
            if self._logfile:
                self._logfile.print_message("The framerate of ("+str(audio.get_framerate())+") of the given file is not appropriate. Framerate is changed to " + str(self._reqFramerate) + " Hz", indent=3, status=1)

        if toconvert is True:
            # Get the expected channel
            idx = audio.extract_channel(0)
            # no more need of input data, can close
            audio.close()

            # Do the job (do not modify the initial channel).
            formatter = ChannelFormatter( audio.get_channel(idx) )
            formatter.set_framerate(self._reqFramerate)
            formatter.set_sampwidth(self._reqSamplewidth)
            formatter.convert()

            # Save the converted channel
            audio_out = Audio()
            audio_out.append_channel( formatter.channel )
            signals.save( outputname, audio_out )

        return toconvert
Example #3
0
parser.add_argument("-o", metavar="file", required=True,  help='Audio Output file name')
parser.add_argument("-bs", default=0, metavar="value", type=float, help='The position (in seconds) when begins the mix, don\'t use with -bf')
parser.add_argument("-es", default=0, metavar="value", type=float, help='The position (in seconds) when ends the mix, don\'t use with -ef')
parser.add_argument("-bf", default=0, metavar="value", type=float, help='The position (in number of frames) when begins the mix, don\'t use with -bs')
parser.add_argument("-ef", default=0, metavar="value", type=float, help='The position (in number of frames) when ends the mix, don\'t use with -es')

# ----------------------------------------------------------------------------

if len(sys.argv) <= 1:
    sys.argv.append('-h')

args = parser.parse_args()
    
# ----------------------------------------------------------------------------

audio_out = Audio()
audio = signals.open(args.w)

if args.bf and args.bs:
    print "bf option and bs option can't be used at the same time !"
    sys.exit(1)

if args.ef and args.es:
    print "ef option and es option can't be used at the same time !"
    sys.exit(1)

if args.bf:
    begin = args.bf
elif args.bs:
    begin = args.bs*audio.get_framerate()
else:
Example #4
0
parser.add_argument("-o", metavar="file", required=True,  help='Audio Output file name')


# ----------------------------------------------------------------------------

if len(sys.argv) <= 1:
    sys.argv.append('-h')

args = parser.parse_args()
    
# ----------------------------------------------------------------------------


mixer = ChannelsMixer()

for inputFile in args.w:
    audio = signals.open(inputFile)
    for i in xrange(audio.get_nchannels()):
        idx = audio.extract_channel(i)
        audio.rewind()
        mixer.append_channel(audio.get_channel(idx))
    
newchannel = mixer.mix()


# Save the converted channel
audio_out = Audio()
audio_out.append_channel( newchannel )
signals.save( args.o, audio_out )

# ----------------------------------------------------------------------------
Example #5
0
    sys.exit(1)

# ----------------------------------------------------------------------------

print (time.strftime("%H:%M:%S"))
audio = signals.open(args.w)

# Get the expected channel
idx = audio.extract_channel(args.c-1)
# no more need of input data, can close
audio.close()
print (time.strftime("%H:%M:%S"))

# Do the job (do not modify the initial channel).
formatter = ChannelFormatter( audio.get_channel(idx) )
if args.r:
    formatter.set_framerate(args.r)
if args.b:
    formatter.set_sampwidth(args.b)
formatter.convert()
print (time.strftime("%H:%M:%S"))

# Save the converted channel
audio_out = Audio()
audio_out.append_channel( formatter.channel )
signals.save( args.o, audio_out )
print (time.strftime("%H:%M:%S"))

# ----------------------------------------------------------------------------

Example #6
0
if verbose > 0:
    p.update(1, "")
    del p
if verbose > 1:
    print "\nEnd mixing channels at %s"%time.strftime('%d/%m/%y %H:%M:%S',time.localtime())

#========================SAVE THE RESULT============================#
p = None
if verbose > 0:
    p = TextProgress()
    p.set_new()
    p.set_header("Saving the output file")
    p.set_fraction(0)
    p.update(0,"")

audio_out = Audio()
audio_out.append_channel( newchannelleft )
audio_out.append_channel( newchannelright )

signals.save( args.o, audio_out )

if verbose > 0:
    p.update(1, "")

# ----------------------------------------------------------------------------

if verbose > 1:
    print "\nEnd process at %s", time.strftime('%d/%m/%y %H:%M:%S',time.localtime())

# ----------------------------------------------------------------------------
Example #7
0
freq = 2000 # Hz
r = 0.98
a1 = -2.0 * r * math.cos(freq / (SAMPLE_RATE / 2.0) * math.pi)
a2 = r * r
filter = [a1, a2]
print filter

n = audioin.get_nframes()
original = struct.unpack('%dh' % n, audioin.read_frames(n))
original = [s / 2.0**15 for s in original]

result = [ 0 for i in range(0, len(filter)) ]
biggest = 1
for sample in original:
        for cpos in range(0, len(filter)):
            sample -= result[len(result) - 1 - cpos] * filter[cpos]
        result.append(sample)
        biggest = max(abs(sample), biggest)

result = [ sample / biggest for sample in result ]
result = [ int(sample * (2.0**15 - 1)) for sample in result ]

# ----------------------------------------------------------------------------

audioout = Audio()
channel = Channel(framerate=SAMPLE_RATE, sampwidth=audioin.get_sampwidth(), frames=struct.pack('%dh' % len(result), *result) )
audioout.append_channel( channel )
signals.save( args.o, audioout)

# ----------------------------------------------------------------------------
Example #8
0
parser.add_argument("-w", metavar="file", required=True,  help='Audio Input file name')
parser.add_argument("-o", metavar="file", required=True,  help='Audio Output file name')
parser.add_argument("-c", metavar="value", type=int, required=True, help='Numero of the channel to extract')


# ----------------------------------------------------------------------------

if len(sys.argv) <= 1:
    sys.argv.append('-h')

args = parser.parse_args()
    
# ----------------------------------------------------------------------------

audio = signals.open(args.w)

if args.c == 0 or args.c > audio.get_nchannels():
    print "Wrong channel value (must be > 0 and < number of channels)"
    sys.exit(1)

idx = audio.extract_channel(args.c-1)



# Save the converted channel
audio_out = Audio()
audio_out.append_channel( audio.get_channel(idx) )
signals.save( args.o, audio_out )

# ----------------------------------------------------------------------------
Example #9
0
    def write_tracks(self, trstracks, output, ext="txt", trsunits=[], trsnames=[], logfile=None):
        """
        Write tracks in an output directory.

        Print only errors in a log file.

        @param trstracks   All tracks as an array of tuples (start,end)
        @param output      Directory name (String)
        @param ext         Tracks file names extension (String)
        @param trsunits    Tracks content (Array of string)
        @param trsnames    Expected tracks file's names (Array of string)
        @param logfile     Log file (sppasLog)

        """
        wavtraks = True
        if not os.path.exists( output ):
            os.mkdir( output )

        # Write text tracks

        for i in range(len(trsunits)):
            trackbasename = ""
            if len(trsnames) > 0:
                # Specific names are given
                trackbasename = os.path.join(output, trsnames[i])
            else:
                trackbasename = os.path.join(output, "track_%.06d" % (i+1))
            if len(trackbasename)>0:
                # Write the transcription track content (if any)
                if len(trsunits)>0:
                    tracktxtname = trackbasename+"."+ext
                    if isinstance(trsunits[0], Transcription):
                        annotationdata.io.write(tracktxtname, trsunits[i])
                    else:
                        encoding='utf-8'
                        with codecs.open(tracktxtname,"w", encoding) as fp:
                            fp.write(trsunits[i])
                elif logfile is not None:
                    logfile.print_message( "Writing track "+tracktxtname,indent=3,status=-1 )
                else:
                    print ( " ... ... ... Writing track "+tracktxtname+": [ERROR]" )

        # Write wav tracks

        if self.channelsil.channel is None:
            return False

        try:
            split_tracks = self.channelsil.track_data( trstracks )
        except Exception:
            logfile.print_message('split tracks failed: wav corrupted',indent=2,status=-1)
            return False

        for i, split_track in enumerate(split_tracks):
            trackbasename = ""
            if len(trsnames) > 0:
                # Specific names are given
                trackbasename = os.path.join(output, trsnames[i])
            else:
                trackbasename = os.path.join(output, "track_%.06d" % (i+1))
            if len(trackbasename)>0:
                # Write the wav track content
                trackwavname = trackbasename+".wav"
                audio_out = Audio()
                audio_out.append_channel(self.channelsil.channel)
                try:
                    signals.save_fragment(trackwavname, audio_out, split_track)
                except Exception as e:
                    if logfile:
                        logfile.print_message('Writing track %s failed with error: %s'%(trackwavname,str(e)), status=-1)
                    else:
                        print 'Writing track %s failed with error: %s'%(trackwavname,str(e))
                    wavtraks = False

        return wavtraks
Example #10
0
    
# ----------------------------------------------------------------------------


equalizer = ChannelsEqualizer()

file = signals.open(args.w[0])
sampwidth = file.get_sampwidth()
framerate = file.get_framerate()

for inputFile in args.w:
    audio = signals.open(inputFile)
    if audio.get_sampwidth() != sampwidth:
        print "Input files must have the same sample width !"
        sys.exit(1)
    if audio.get_framerate() != framerate:
        print "Input files must have the same framerate !"
        sys.exit(1)
    idx = audio.extract_channel(1)
    equalizer.append_channel(audio.get_channel(idx))
    
equalizer.equalize()

# Save the converted channel
for i, chan in enumerate(equalizer.channels):
    audio_out = Audio()
    audio_out.append_channel( chan )
    filename, extension = os.path.splitext(args.w[i])
    signals.save(filename + "EQUAL" + extension, audio_out)

# ----------------------------------------------------------------------------