gpt4 book ai didi

Java 复制剪辑

转载 作者:行者123 更新时间:2023-11-29 08:23:38 27 4
gpt4 key购买 nike

我发现很多主题都在建议和讨论克隆,但我一直无法真正实现可以复制我的 Clip 对象的方法。

这是我尝试过的:

// ... setting up class ...

MyClip GunClip = new MyClip();

GunClip.set(AudioSystem.getClip());

AudioInputStream inputStream = AudioSystem.getAudioInputStream(new BufferedInputStream(getClass().getResourceAsStream("/Resources/sound/Laser.wav")));

GunClip.dummy.open(inputStream);
// ...

然后当一个事件被触发时,我想重复播放那个声音。所以我尝试复制它:

class MyClip implements Cloneable {

Clip dummy;

public MyClip() {

}

public Clip get() {
return dummy;
}

public void set(Clip c) {
this.dummy = c;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}

}

我按照 this 中的建议实现了 Cloneable 类主题。

然后我在播放之前克隆它:

MyClip c = (MyClip) GunClip.clone();

c.dummy.setFramePosition(0);
c.dummy.start();

但即使现在它也不起作用......

编辑:我已经弄清楚为什么它不起作用,这是因为它不是深度克隆,并且原始 GunClip 使用的 InputStream 没有被克隆。但由于 Clip 是一个抽象接口(interface),因此克隆它可能比正常情况下更难。

最佳答案

class MyClip implements Cloneable {

Clip dummy;

public MyClip() {

}

public Clip get() {
return dummy;
}

public void set(Clip c) {
this.dummy = c;
}

@Override
protected Object clone() throws CloneNotSupportedException {
return super.clone();
}
}

如果您编写这样的代码,您基本上是在说“Object 类知道我的自定义类的所有信息,包括如何构建它”。当然不是这样。

您需要根据需要调整克隆方法:

class MyClip implements Cloneable {

Clip dummy;

public MyClip() {

}

public Clip get() {
return dummy;
}

public void set(Clip c) {
this.dummy = c;
}

@Override
protected Object clone() throws CloneNotSupportedException {
MyClip clone = new MyClip(); // create a new instance of your class
clone.set(this.dummy); // make sure it has the same value for 'dummy'
// I would suggest improvement on your setter and getter name, though
return clone; // This returns an instance of MyClip, which has the exact same
// state as your current, but is a clone, and not the same instance.
}

}

为了调用它,你需要这样的东西:

public void getClone(MyClip original) {
MyClip Clone = (MyClip)original.clone();
}

编辑: 根据你的问题,原件的“虚拟”也被感染,如果你想防止这种情况发生,只需让你的 Clip 类也实现 Cloneable,然后将你的将方法克隆到这里:

@Override
protected Object clone() throws CloneNotSupportedException {
MyClip clone = new MyClip();
clone.set(this.dummy == null ? null : this.dummy.clone());
return clone;
}

关于Java 复制剪辑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55351126/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com