1

我做了这门课:

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“唯一”对象结束。“强制”新创建对象的类型的方法是什么?

以防万一您需要它:

class AudioSegment(object):
    def __add__(self, arg):
        if isinstance(arg, AudioSegment):
            return self.append(arg, crossfade=0)
        else:
            return self.apply_gain(arg)
4

1 回答 1

1

看起来问题是AudioSegment._spawn()

它无条件地返回一个简单的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)

复制和粘贴当然不是一个好习惯,但它确实有效。

Note, however, that it introduces an asymmetry, because AudioSegmentCustom + AudioSegment returns an AudioSegmentCustom, while AudioSegment + AudioSegmentCustom returns an AudioSegment. This --once more-- can be fixed by additionally providing __radd__() in AudioSegmentCustom. It will be called before AudioSegment.__add__().

于 2016-05-08T11:02:21.087 回答