使用Python tempfiles,为什么是.mkstemp工作正常时会给我错误
我试图使用Sox Transformer编写一些代码以首先处理两个音频示例,然后使用Sox Combiner组合两个音频文件。我还试图在内存中首先进行处理以加快事情的速度。
使用 .temporaryFile()
和 .pooledTemporaryFile()
时,我会遇到此错误
trackback(最近的最新调用):文件“ ...”,第128行,in< module> generate_new_audio_files(user_library_folder_pathlist,new_folder_path,file_count)文件“ ...”,第101行,在generate_new_new_audio_files bombine_two_files_files_mild(sample1_file_path,sampe2_file_path,sampe2_file_path,new_folder_pathiles),new_folder_ pather in ... 1_audio = tempfile.spooledtemporaryfile( )value error:没有足够的值解开包装(预期2,获得0)
这是我的代码:
def combine_two_files_mild(file_path_1, file_path_2, parent_folder_path, count=None):
combiner = sox.Combiner()
tfm1 = sox.Transformer()
tfm2 = sox.Transformer()
tfm1.set_input_format(rate=44100)
tfm2.set_input_format(rate=44100)
combiner.set_input_format(channels=[2, 2])
combiner.gain(normalize=True)
# will eventually insert here some randomized settings for the two transformers
# this determins the file category based on it's file name
file_main_category, file_sub_category = Category.get_file_category(file_path_1)
sorted_file_folder = parent_folder_path + "/" + file_main_category + "/" + file_sub_category
new_file_path = sorted_file_folder + "/" + file_sub_category + " Combined " + \
str(count + 1) + " Mild.wav"
# load the audio data for the two samples
_, sample1_audio = tempfile.SpooledTemporaryFile()
tfm1.build(file_path_1, sample1_audio)
_, sample2_audio = tempfile.SpooledTemporaryFile()
tfm2.build(file_path_2, sample2_audio)
# combine the two files and write to disk
combiner.build([sample1_audio, sample2_audio], new_file_path, 'mix-power',
input_volumes=[0.5, 0.5])
# clear the 'memory'
os.remove(sample1_audio)
os.remove(sample2_audio)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
spooledtemporaryFile
的API不同于mkstemp
。mkstemp
返回两个对象的元组(您将其设置为_
和sample1_audio
)。spooledtemporaryfile
让您使用。通常spooledtemporaryFile
和临时file
被用作上下文管理器,例如:请注意,在使用 block block之后,临时文件将被删除,因此要么保留您需要此块中需要临时文件的所有代码,也可以手动处理文件打开和关闭:
此外,
tempfile
模块是专门为创建临时文件而自动删除的临时文件不再需要,因此您不应该在最后需要os.remove
的电话!The API for
SpooledTemporaryFile
is different frommkstemp
.mkstemp
returns a tuple of two objects (which you are setting as_
andsample1_audio
respectively).SpooledTemporaryFile
will return a single file-like object for you to use. UsuallySpooledTemporaryFile
andTemporaryFile
are used as context managers like so:Note that after the
with
block, the temporary file will be deleted, so either keep all of your code that requires the temporary files in this block, or you can manually handle the file opening and closing yourself:Additionally, the
tempfile
module is specifically made to create temporary files which are removed automatically when they are no longer needed, so you should not need your calls toos.remove
at the end!