jam*_*mes 7 audio android media-player soundpool android-audiomanager
我试图在android中同时播放两个声音.我创建了两个MediaPlayers并使用下面的代码.他们正在一个接一个播放.或者不是一个接一个但是有点延迟到彼此.
private void playSound(){
if (mp1 != null) {
mp1.release();
}
if (mp2 != null) {
mp2.release();
}
mp1 = MediaPlayer.create(this, soundArray[0]);
mp2 = MediaPlayer.create(this, soundArray[3]);
mp1.start();
mp2.start();
}
Run Code Online (Sandbox Code Playgroud)
谢谢
同时做两件事是..困难的。在单线程环境中,操作系统需要在线程之间跳转以模拟它们同时运行。因此,为了能够“同时”运行它们,您需要启动两个线程并等待它们到达应该同步的位置,然后让两个线程继续运行。
另一种解决方案是合并两个声音流,这样听起来就像是两个声音在播放,而实际上是一个声音。虽然我对声音处理不太精通,而且在 Android 上也更不行……
第一个的解决方案是生成两个线程,启动它们,然后使用 andwait()让notify()它们MediaPlayer.start()同时调用,可能使用Lock类。
好的,这是一个关于如何同步两个线程的长示例(基于此处的示例:
import java.util.concurrent.locks.*;
class SynchronizeTest implements Runnable {
public static void main(String[] args) {
final ReentrantLock lock = new ReentrantLock();
final Condition cond = lock.newCondition();
new Thread(new SynchronizeTest(1, lock, cond)).start();
new Thread(new SynchronizeTest(2, lock, cond)).start();
}
private final int number;
private final ReentrantLock lock;
private final Condition cond;
public SynchronizeTest(int number, ReentrantLock lock, Condition cond) {
this.number = number;
this.lock = lock;
this.cond = cond;
}
public void run() {
try {
if (number == 1) {
put();
}
else {
take();
}
}
catch (InterruptedException ie) { }
}
public void put() throws InterruptedException {
lock.lock();
try {
cond.await();
} finally {
lock.unlock();
}
System.out.println(number);
}
public void take() throws InterruptedException {
lock.lock();
// wait for put to take the lock
Thread.sleep(300);
try {
cond.signal();
} finally {
lock.unlock();
}
System.out.println(number);
}
}
Run Code Online (Sandbox Code Playgroud)
这可能可以更简单地编码,但我最近没有做过那么多 Java 编码..:-(
| 归档时间: |
|
| 查看次数: |
5779 次 |
| 最近记录: |