Lescott
Lescott

Reputation: 11

splititng 24 bit depth wav sound in interval in pure python

Currently I'm making some small research on wave files using only Python. One problem I can't solve right now, is splitting wav data. format file with 24 bit sound depth correctly.

So the basic idea is: given t1 - start and t2 -end, and I need to get the slice, which is quite clear.

def split_in_interval(self, start, end):
    start *= ONE_SEC_MS
    end *= ONE_SEC_MS
    header = self.wav_header.header_description
    infile = open(self.file_name, 'rb')

    rate = header['sample_rate']
    frames_per_m_sec = rate // 1000
    length = (end - start) * frames_per_m_sec
    start_ms = start * frames_per_m_sec

    name_str = self._naming_fragment(start, end)
    out_file = open(name_str, 'wb')

    # as the size changes - need to recalculate only last part of header,
    # it takes 4 last bytes of header
    out_file.write(infile.read(WAV_HEADER - 4))

    size = length * header['block_align']
    # header['num_channels'] * width
    packed_size = struct.pack('<L', size)
    out_file.write(packed_size)

    anchor = infile.tell()
    infile.seek(anchor + start_ms)

    out_file.write(infile.read(size))
    out_file.close()
    infile.close()

I think my code is quite straight forward and it works fine with 16 and 8 bits depth sounds, but after I tried 24 - it fails.

I take rate and convert it into milliseconds, my Start and End parameters also convert to ms. And after, basis on this calculations, assuming they're right I'm finding start_point in my source audio and then write from this point to the end. What may I do wrong? How to solve this problem, using only Python without any external libraries.

Thanks, in advance.

Upvotes: 1

Views: 347

Answers (1)

Matthias
Matthias

Reputation: 4914

If you could use an external library, I'd recommend the soundfile module, which handles 24-bit files out-of-the-box.

If you really want to use pure Python, you should at least use the built-in wave module, which at least takes care of the header for you. You'll still have to convert the raw bytes into something meaningful on your own.

It's hard to tell what's going wrong in your case, because you are showing only a part of your code. You should show the code that works for 16 and 8 bit and doesn't work for 24. I don't see any mention of bit depth in your code.

It probably helps if you have a look at my tutorial about the wave module.

Upvotes: 0

Related Questions