Doing two things at exactly the same time is ..difficult. In a one threaded environment the OS needs to jump between threads to simulate them running at the same time. So to be able to run them at the "same time", you need to start two threads and wait for them to arrive at the point where they should be synchronized and then let both threads now that they should continue.
Another solution would be to merge the two sound streams so that it sounds like if it's two sounds playing when it's actually one. Altough I'm not that proficient in sound manipulation, and definitely not on Android...
A solution for the first would be to spawn two threads, start them both and then use a wait()
and notify()
to get them to call MediaPlayer.start()
at the same time, possibly with the Lock class.
Okay, so a long example of how to synchronize two threads (based on example here are:
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);
}
}
This can probably be coded much simpler, but I haven't done that much Java coding lately.. :-(