def SaveChannel(self, parentfilename, period=False):
        """
        Save the channel in an audio file.

        @param parentfilename (str)
        @param period (bool) Save a portion of the channel only

        """
        s = None
        e = None
        if period is True:
            dlg = PeriodChooser( self, self._prefs, 0., float(self._channel.get_nframes())/float(self._channel.get_framerate()) )
            answer = dlg.ShowModal()
            if answer == wx.ID_OK:
                (s,e) = dlg.GetValues()
                try:
                    s = float(s)
                    e = float(e)
                    if e < s: raise Exception
                except Exception:
                    ShowInformation( self, self._prefs, "Error in the definition of the portion of time.", style=wx.ICON_ERROR)
                    return
            dlg.Destroy()
            if answer != wx.ID_OK:
                return

        newfilename = SaveAsAudioFile()

        # If it is the OK response, process the data.
        if newfilename is not None:
            if newfilename == parentfilename:
                ShowInformation( self, self._prefs, "Assigning the current file name is forbidden. Choose a new file name.", style=wx.ICON_ERROR)
                return

            # Create a formatted channel
            try:
                channel = self.ApplyChanges(s,e)
            except Exception as e:
                ShowInformation( self, self._prefs, "Error while formatting the channel: %s"%str(e), style=wx.ICON_ERROR)
                return

            message = "File %s saved successfully."%newfilename
            if channel is None:
                channel = self._channel
            else:
                message +="\nYou can now open it with AudioRoamer to see your changes!"

            # Save the channel
            try:
                audio = AudioPCM()
                audio.append_channel(channel)
                audiodata.io.save(newfilename, audio)
            except Exception as e:
                message = "File not saved. Error: %s"%str(e)
            else:
                # Update members
                self._filename = newfilename

            ShowInformation( self, self._prefs, message, style=wx.ICON_ERROR)
Exemple #2
0
def write_channel(audioname, channel):
    """
    Write a channel as an audio file.

    @param audioname (str - IN) Audio file name to write
    @param channel (Channel - IN) Channel to be saved

    """
    audio_out = AudioPCM()
    audio_out.append_channel( channel )
    audiodata.io.save( audioname, audio_out )
Exemple #3
0
    def test_Save(self):
        cidx = self._sample_1.extract_channel(0)
        channel = self._sample_1.get_channel(cidx)
        audio = AudioPCM()
        audio.append_channel( channel )
        audiodata.io.save( sample_new, audio )
        savedaudio = audiodata.io.open( sample_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)

        savedaudio.close()
        os.remove( sample_new )
Exemple #4
0
    def write_audio_tracks(self, ipustrs, ipusaudio, output, extension):
        """
        Write the audio in track files.

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

        if extension is None:
            raise IOError('An extension is required to write audio tracks.')

        if ipusaudio.get_channel() is None:
            return

        try:
            split_tracks = ipusaudio.chansil.track_data( self.tracks )
        except Exception as e:
            raise Exception('Split into tracks failed: audio corrupted: %s'%e)

        names = ipustrs.get_names()

        # Write audio tracks
        for i, split_track in enumerate(split_tracks):
            trackbasename = ""
            if len(names) > 0 and len(names[i])>0:
                # Specific names are given
                trackbasename = os.path.join(output, names[i])
            else:
                trackbasename = os.path.join(output, "track_%.06d" % (i+1))

            trackwavname = trackbasename+"."+extension
            audio_out = AudioPCM()
            audio_out.append_channel(ipusaudio.get_channel())
            try:
                audiodata.io.save_fragment(trackwavname, audio_out, split_track)
            except Exception as e:
                raise Exception("Can't write track: %s. Error is %s"%(trackwavname,e))
Exemple #5
0
    def test_channels(self):
        a1 = audiodata.io.open(sample_1)
        a2 = AudioPCM()
        a3 = audiodata.io.open(sample_3)

        # Test extract_channel
        with self.assertRaises(AudioDataError):
            a2.extract_channel(0)
        with self.assertRaises(AudioDataError):
            a1.extract_channel(2)

        cidx1 = a3.extract_channel()
        cidx2 = a3.extract_channel( 1 )

        c1 = a3.get_channel(cidx1)
        c2 = a3.get_channel(cidx2)

        self.assertEqual(0, a2.append_channel( c1 ) )
        self.assertEqual(1, a2.append_channel( c2 ) )
        a2.insert_channel( 0, c1 )
        self.assertTrue( a2.verify_channels())
Exemple #6
0
 def test_set_get(self):
     a1 = audiodata.io.open(sample_1)
     a2 = AudioPCM()
     a2.Set(a1)
     self.assertEqual(a1.get_channels(), a2.get_channels())
     self.assertEqual(a1.get_audiofp(), a2.get_audiofp())
Exemple #7
0
    def __init__(self):
        """
        Constructor.

        """
        AudioPCM.__init__(self)
Exemple #8
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 = AudioPCM()
channel = Channel(framerate=SAMPLE_RATE, sampwidth=audioin.get_sampwidth(), frames=struct.pack('%dh' % len(result), *result) )
audioout.append_channel( channel )
audiodata.save( args.o, audioout)

# ----------------------------------------------------------------------------
Exemple #9
0
parser.add_argument("-w", metavar="file", nargs='+', required=True,  help='Audio Input file name')
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 = audiodata.open(inputFile)
    idx = audio.extract_channel(0)
    mixer.append_channel(audio.get_channel(idx))

newchannel = mixer.mix()


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

# ----------------------------------------------------------------------------
Exemple #10
0
    sys.exit(1)

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

print (time.strftime("%H:%M:%S"))
audio = audiodata.io.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 = AudioPCM()
audio_out.append_channel( formatter.channel )
audiodata.save( args.o, audio_out )
print (time.strftime("%H:%M:%S"))

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

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 = AudioPCM()
audio = audiodata.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:
Exemple #12
0
parser = ArgumentParser(usage="%s -w input file -o output file -c channel" % os.path.basename(PROGRAM), description="A script to extract a channel from an audio file")

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 = audiodata.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 = AudioPCM()
audio_out.append_channel( audio.get_channel(idx) )
audiodata.save( args.o, audio_out )

# ----------------------------------------------------------------------------
Exemple #13
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 = AudioPCM()
audio_out.append_channel( newchannelleft )
audio_out.append_channel( newchannelright )

audiodata.io.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())

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