我上过这门课:
class AudioSegmentCustom(AudioSegment):
def fade_override(self, seg, fade_len=100):
seg1, seg2 = AudioSegment._sync(self, seg)
final = seg1[:-fade_len]
a_fin = seg1[-fade_len:].fade(to_gain=-120, start=0, end=float('inf'))
a_fin *= seg2[:fade_len]
return (final + a_fin) + seg2[fade_len:]
我面临的问题是,当我创建一些AudioSegmentCustom
变量时,如果我“添加”它们,add
操作将返回其原始父类型=AudioSegment
因此,以下代码不起作用:
final = AudioSegmentCustom.from_mp3(mp3_src) + AudioSegment.from_mp3(mp3_other)
final = final.fade_override(...blabla...)
因为我得到:
'AudioSegment' object has no attribute 'fade_override'
…尽管我从一个AudioSegmentCustom
对象开始,但我以AudioSegment
“only”对象结束。
如何“强制”新建对象的类型?你知道吗
以防万一:
class AudioSegment(object):
def __add__(self, arg):
if isinstance(arg, AudioSegment):
return self.append(arg, crossfade=0)
else:
return self.apply_gain(arg)
看起来问题是^{} 。你知道吗
它无条件地返回一个基本的
AudioSegment
实例。因为它是一个普通方法,所以可以在AudioSegmentCustom
中重写它:复制和粘贴当然不是一个好的做法,但它确实起到了作用。你知道吗
但是请注意,它引入了一种不对称性,因为
AudioSegmentCustom + AudioSegment
返回AudioSegmentCustom
,而AudioSegment + AudioSegmentCustom
返回AudioSegment
。 可以通过在AudioSegmentCustom
中额外提供__radd__()
来解决这个问题。它将在AudioSegment.__add__()
之前调用。你知道吗相关问题 更多 >
编程相关推荐