如何强制上课?

2024-10-01 04:48:55 发布

您现在位置:Python中文网/ 问答频道 /正文

我上过这门课:

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)

Tags: 对象selflenreturnargmp3classfinal
1条回答
网友
1楼 · 发布于 2024-10-01 04:48:55

看起来问题是^{}。你知道吗

它无条件地返回一个基本的AudioSegment实例。因为它是一个普通方法,所以可以在AudioSegmentCustom中重写它:

def _spawn(self, data, overrides={}):
    """
    Creates a new audio segment using the metadata from the current one
    and the data passed in. Should be used whenever an AudioSegment is
    being returned by an operation that would alters the current one,
    since AudioSegment objects are immutable.
    """
    # accept lists of data chunks
    if isinstance(data, list):
        data = b''.join(data)

    # accept file-like objects
    if hasattr(data, 'read'):
        if hasattr(data, 'seek'):
            data.seek(0)
        data = data.read()

    metadata = {
        'sample_width': self.sample_width,
        'frame_rate': self.frame_rate,
        'frame_width': self.frame_width,
        'channels': self.channels
    }
    metadata.update(overrides)
    return self.__class__(data=data, metadata=metadata)

复制和粘贴当然不是一个好的做法,但它确实起到了作用。你知道吗

但是请注意,它引入了一种不对称性,因为AudioSegmentCustom + AudioSegment返回AudioSegmentCustom,而AudioSegment + AudioSegmentCustom返回AudioSegment。 可以通过在AudioSegmentCustom中额外提供__radd__()来解决这个问题。它将在AudioSegment.__add__()之前调用。你知道吗

相关问题 更多 >