Reputation: 307
I've faced issue with playing short sound clip with java. Any advice?
public static void playAll(String note, String beat, String chord) {
try {
AudioInputStream audioInputSoloNote = AudioSystem.getAudioInputStream(new File(
"C:/java_support/solo_sound/"+note+"_"+beat+".wav").getAbsoluteFile());
AudioFormat formatNote = audioInputSoloNote.getFormat();
AudioInputStream audioInputSoloChord = AudioSystem.getAudioInputStream(new File(
"C:/java_support/solo_chord/"+chord+".wav").getAbsoluteFile());
Clip clipSolo = AudioSystem.getClip();
clipSolo.open(audioInputSoloNote);
clipSolo.start();
Clip clipChord = AudioSystem.getClip();
clipChord.open(audioInputSoloChord);
clipChord.start();
long frames = audioInputSoloNote.getFrameLength();
double durationInSeconds = ((frames + 0.0) / formatNote.getFrameRate());
sleep((long) durationInSeconds * 1000);
clipSolo.stop();
clipChord.stop();
} catch(Exception ex) {
System.out.println("Error with playing sound.");
ex.printStackTrace();
}
}
Problem: I am writing an application for my studies about "AI" implementation in the creation of classical music. There is 3 different notes (from duration perspective) - Half (1.2 sec), Quarter (0.6 sec) and Eighth (0.3 sec). This code plays Half and Querter notes in correct manner, however, when it comes to Eighth notes, it just skips them.
I.e:
C Quarter C --> play (0.6sec duration)
F Eighth F --> skip (0.3sec)
E Eighth C --> skip (0.3sec)
F Quarter F --> play (0.6sec)
F Quarter Dm --> play (0.6sec)
C Half F --> play (1.2sec)
... ... ...
Solution might me to increase durationInSeconds, however, it will extend all sounds and I don't want to do it.
Also I'd like to find out adaptation to android: i.e. I want to play 7 short sounds in order.
private void playNotes (ArrayList<Data> list) {
SoundPool sp = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
for (int i = 0; i < list.size(); i++) {
String note = list.get(i).getNote().toLowerCase()+"_eighth";
int resID = getResources().getIdentifier(note, "raw",
getPackageName());
int soundId = sp.load(this, resID, 1);
sp.play(soundId);
MediaPlayer mPlayer = MediaPlayer.create(this, resID);
mPlayer.start();
}
}
what I get is all sound clips are played at the same time. How to fix it?
Upvotes: 1
Views: 119
Reputation: 307
Have found a solution. Don't know if it is broken code, however, for my project works perfectly
try
{
Thread.sleep(1000);
}
catch(InterruptedException ex)
{
Thread.currentThread().interrupt();
}
Upvotes: 0