简体   繁体   中英

Writing multiple sound files into a single file in python

I have three sound files for example a.wav, b.wav and c.wav . I want to write them into a single file for example all.xmv (extension could be different too) and when I need I want to extract one of them and I want to play it (for example I want to play a.wav and extract it form all.xmv).

How can I do it in python. I have heard that there is a function named blockwrite in Delphi and it does the thing that I want. Is there a function in python that is like blockwrite in Delphi or how can I write these files and play them?

If the archive idea (which is btw, the best answer to your question) doesn't suit you, you can fuse the data from several files in one file, eg by writing consecutive blocks of binary data (thus creating an uncompressed archive!)

Let paths be a list of files that should be concatenated:

import io
import os

offsets = [] # the offsets that should be kept for later file navigation
last_offset = 0

fout = io.FileIO(out_path, 'w')
for path in paths:
    f = io.FileIO(path) # stream IO
    fout.write(f.read())
    f.close()
    last_offset += os.path.getsize(path)
    offsets.append(last_offset)       
fout.close()

# Pseudo: write the offsets to separate file e.g. by pickling
# ...

# reading the data, given that offsets[] list is available
file_ID = 10                   # e.g. you need to read 10th file
f = io.FileIO(path)    
f.seek(offsets[file_ID - 1])   # seek to required position 
read_size = offsets[filed_ID] - offsets[file_ID - 1]  # get the file size
data = f.read(read_size)       # here we are! 
f.close()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM