Beispiel #1
0
 def test_make_chunks(self):
     seg = self.seg1
     chunks = make_chunks(seg, 100)
     seg2 = chunks[0]
     for chunk in chunks[1:]:
         seg2 += chunk
     self.assertEqual(len(seg), len(seg2))
Beispiel #2
0
 def play_speech(self, speech_file):
     """
     It open the audio and make the "queue" of chunks from it
     """
     self._speaking_chunks = make_chunks(
         AudioSegment.from_wav(speech_file), 1000)
     self._is_speaking = True
Beispiel #3
0
 def __get_stream(self):
     self.__segment = AudioSegment.from_file(self.__path)
     self.__chunks = make_chunks(self.__segment, 100)
     return self.__pyaudio.open(format=self.__pyaudio.get_format_from_width(self.__segment.sample_width),
                                channels=self.__segment.channels,
                                rate=self.__segment.frame_rate,
                                output=True)
Beispiel #4
0
 def play_music(self, music_file):
     """
     It open the audio and make the "queue" of chunks from it
     """
     self._music_chunks = make_chunks(
         AudioSegment.from_wav(music_file), 1000)
     self._is_music = True
Beispiel #5
0
def chunks():
    audio = AudioSegment.from_mp3("track2.mp3")
    audio = audio
    chunks = make_chunks(audio, 200)
    empty = audio[:0]
    for chunk in chunks:
        if chunk.rms > 430:
            empty += chunk
    empty.export("test.mp3", format="mp3")
Beispiel #6
0
def main():
    # Load audio file and print the length
    audio = AudioSegment.from_wav("C:\MB Track 32.wav")
    print("audio length:\t\t" + str(audio.__len__() / 1000) + "seconds")

    # Strip off the first few seconds and create chunks of audio
    # audio = audio[4000:]


    chuck_start_end_list = []
    running = True
    average_loudness = audio.rms
    # silence_threshold = average_loudness * db_to_float(-21)
    chunks = make_chunks(audio, splicing_resolution)
    print("chunk list length:\t" + str(len(chunks)))

    build = audio[:0]
    i = 0
    start = 0
    stop = 0
    while i < (len(chunks)):
        start_stop = [0, 0]
        if chunks[i].rms <= silence_threshold:
            while i < (len(chunks)) and chunks[i].rms <= silence_threshold:
                print("low" + str(i))
                print(chunks[i].rms)
                i += 1
            start = i
        else:
            while i < (len(chunks)) and chunks[i].rms > silence_threshold:
                print("high" + str(i))
                print(chunks[i].rms)
                i += 1
        stop = i
        # print("pass")
        if ( start != stop):
            chuck_start_end_list.append([start, stop])
    # build = chunk_list[i]
    #     build.export(("test/test{0}.mp3".format(str(i))), format="mp3")
    # build.export("test2.mp3", format="mp3")


    print((chuck_start_end_list))
    print("Chuck start stop list length: " + str(len(chuck_start_end_list)))
    print("silence threshold:\t" + str(silence_threshold))

    # For testing only -- prints segment sizes, showing larger segment
    large_chunks = 0
    for chunk in chuck_start_end_list:
        size = (chunk[1] - chunk[0])

        if size > 32:
            print("----------" + str(size))
            large_chunks += 1
        else:
            print(size)
    print(large_chunks)
    def _play(self, start, length):
        self.isplaying = True
        if AudioSegment:
            millisecondchunk = 50 / 1000.0
            playchunk = self.pydubfile[start*1000.0:(start+length)*1000.0] - (60 - (60 * (self.volume/100.0)))
            self.time = start
            self.audio.play(playchunk.get_array_of_samples(), blocking=False)

            # For some reason it does not like the seperated chunks, so we play it non-
            # We might be able to use self.audio.get_stream().time to improve accuracy
            for chunks in make_chunks(playchunk, millisecondchunk*1000):
                self.time += millisecondchunk

                time.sleep(millisecondchunk)
                if not self.isplaying:
                    break
                if self.time >= start+length:
                    break
        else:
            startframe = int(round(start * self.wave_reference.getframerate()))
            samplelen = int(round(length * self.wave_reference.getframerate()))
            remaining = samplelen
            chunk = 1024
            try:
                self.wave_reference.setpos(startframe)
            except wave.Error:
                self.isplaying = False
                return

            if remaining >= 1024:
                data = audioop.mul(self.wave_reference.readframes(chunk),self.wave_reference.getsampwidth(), self.volume/100.0)
                remaining -= chunk
            else:
                data = audioop.mul(self.wave_reference.readframes(remaining),self.wave_reference.getsampwidth(), self.volume/100.0)
                remaining = 0

            # play stream
            self.audio.play(data.get_array_of_samples(), blocking=False)

            while len(data) > 0 and self.isplaying:

                time.sleep(float(self.wave_reference.getframerate()))
                self.time = float(self.wave_reference.tell()) / float(self.wave_reference.getframerate())
                if remaining >= 1024:
                    data = audioop.mul(self.wave_reference.readframes(chunk),self.wave_reference.getsampwidth(), self.volume/100.0)
                    remaining -= chunk
                else:
                    data = audioop.mul(self.wave_reference.readframes(remaining),self.wave_reference.getsampwidth(), self.volume/100.0)
                    remaining = 0

        self.audio.stop()
        self.isplaying = False
Beispiel #8
0
def mix_segments(segments, slice_length=500):
    """Mixes two tracks together

    Given two tracks 1 and 2, output becomes something like this:
    1 2 1 2 1 2 1 2...
    """
    segments_count = len(segments)
    # Cut to the shortest segment
    shortest_length = min(len(segment) for segment in segments)
    segments = [segment[:shortest_length] for segment in segments]
    slices = [make_chunks(segment, slice_length) for segment in segments]
    first = slices[0][0]
    for i, s in enumerate(slices[0][1:], start=1):
        first += slices[i % segments_count][i]
    return first
Beispiel #9
0
def volume_changer(segment, slice_length=250):
    """Changes volume of the track on set interval

    The track becomes something like this:
    H L H L H L H L...
    where H means high volume, and L stands for low (reduced) volume.
    """
    # Split segment into equally sized slices
    slices = make_chunks(segment, slice_length)
    result = slices[0]
    for i, s in enumerate(slices[1:]):
        if i % 2 == 0:
            s -= 15
        result += s
    return result
Beispiel #10
0
    def run(self):
        player = pyaudio.PyAudio()
        stream = player.open(
            format=player.get_format_from_width(self.segment.sample_width),
            channels=self.segment.channels,
            rate=self.segment.frame_rate,
            output=True,
        )

        # break audio into quarter-second chunks (to allows interrupts)
        for i, chunk in enumerate(make_chunks(self.segment, 250)):
            if self._notifier:
                self._notifier(i*250)
            if not self._playing:
                break
            stream.write(chunk._data)

        stream.stop_stream()
        stream.close()
        player.terminate()
Beispiel #11
0
def main():
    x = pause_threshold
    audio = AudioSegment.from_wav("MB Track 3.wav")
    audio = audio[4000:]
    chunks = make_chunks(audio, splicing_resolution)
    build = audio[:0]
    # silence_threshold = audio.rms * db_to_float(-22.5)
    print(silence_threshold)
    resets = 0
    chunk_list = []
    for i in range(len(chunks)):

        if chunks[i].rms < silence_threshold:
            if (0 > x):
                x = pause_threshold
                print("reset x")
                resets += 1
                chunk_list.append(build)
                build = audio[:0]
            else:

                print("decrement x")
            x -= 1

        else:

            build += chunks[i]
    build = audio[:0]
    print(len(chunk_list))
    for i in range(1, len(chunk_list)):
        print("ex")
        build = chunk_list[i]
        build.export(("test/test{0}.mp3".format(str(i))), format="mp3")
    print("resets: " + str(resets))
    build.export("test2.mp3", format="mp3")
    print("silence threshold: " + str(silence_threshold))
Beispiel #12
0
from pydub import AudioSegment
from pydub.utils import make_chunks

myaudio = AudioSegment.from_file("artofwar.wav" , "wav")
chunk_length_ms = 100000 # pydub calculates in millisec
chunks = make_chunks(myaudio, chunk_length_ms) #Make chunks of one sec

#Export all of the individual chunks as wav files
licz = 0
for i, chunk in enumerate(chunks):
    chunk_name = "art{0}.wav".format(i)
    print "exporting", chunk_name
    chunk.export(chunk_name, format="wav")
    licz +=2
    if licz > 0:
        break
print "sample_width=", sample_width 
print "channel_count=", channel_count
print "duration_in_sec=", duration_in_sec 
print "frame_rate=", sample_rate
bit_rate =16  #assumption , you can extract from mediainfo("test.wav") dynamically


wav_file_size = (sample_rate * bit_rate * channel_count * duration_in_sec) / 8
print "wav_file_size = ",wav_file_size


file_split_size = 10000000  # 10Mb OR 10, 000, 000 bytes
total_chunks =  wav_file_size // file_split_size

#Get chunk size by following method #There are more than one ofcourse
#for  duration_in_sec (X) --&gt;  wav_file_size (Y)
#So   whats duration in sec  (K) --&gt; for file size of 10Mb
#  K = X * 10Mb / Y

chunk_length_in_sec = math.ceil((duration_in_sec * 10000000 ) /wav_file_size)   #in sec
chunk_length_ms = chunk_length_in_sec * 1000
chunks = make_chunks(myaudio, chunk_length_ms)

#Export all of the individual chunks as wav files

for i, chunk in enumerate(chunks):
    chunk_name = "chunk{0}.mp3".format(i)
    print "exporting", chunk_name
    chunk.export(chunk_name, format="mp3")
import argparse
import os
from pydub import AudioSegment
from pydub.utils import make_chunks

parser = argparse.ArgumentParser(description='A script for splitting audio files into segements')
parser.add_argument('-p', '--path', help='The path to the folder to process', required=True)
# An example would be: --path '/Users/danielpett/githubProjects/britishMuseumSoundCloud/originals/unprocessed/'
parser.add_argument('-d', '--destination', help='The destination folder', required=True)
# An example would be: --path '/Users/danielpett/githubProjects/britishMuseumSoundCloud/chunked/'
parser.add_argument('-l', '--length', help='Length of chunk', required=True)
# An example would be --length 10000

# Parse arguments
args = parser.parse_args()
path = args.path

# Loop through the files
for file in os.listdir(path):
    print('Now processing: ' + file)
    myaudio = AudioSegment.from_file(os.path.join(path,file), "mp3")
    # Make chunks of length specified
    chunk_length_ms = args.length
    chunks = make_chunks(myaudio, int(args.length))
    for i, chunk in enumerate(chunks):
        processedFileName = os.path.splitext(file)[0]
        chunk_name = args.destination + processedFileName + "_Chunk{0}.mp3".format(i)
        print "Now exporting: " , chunk_name
        chunk.export(chunk_name, format="mp3")