2
$\begingroup$

I use mathematica to play the Inventions No8 by Bach. I want to play the two parts (by right and left hands )at the same time. But I don't know how to do it. Can you help me? Thank you!

 - Clear["`*"]
{a, b, c, d} = 0.8*{1, 0.5, 0.25, 0.125};

{c4, d4, e4, f4, g4, a4, b4} = {0, 2, 4, 5, 7, 9, 11};
{c5, d5, e5, f5, g5, a5, b5} = {c4, d4, e4, f4, g4, a4, b4} + 12;
b\[Flat] = 10;

time1 = Join[ConstantArray[b, 7], ConstantArray[c, 10], 
   ConstantArray[b, 6]];
note1 = {None, f4, a4, f4, c5, f4, f5,
    e5, d5, c5, d5, c5, b4,
    a4, b4, a4, g4,
    f4, a4, c5, a4, f5, c5} /. {b4 -> b\[Flat]};


Sound@MapThread[SoundNote[#1, #2, "Piano"] &, {note1, time1}]
Sound@MapThread[
  SoundNote[#1, #2, "Piano"] &, {Join[
    ConstantArray[None, 4], (note1 - 12) /. {None - 12 -> None}], 
   Join[ConstantArray[b, 4], time1]}]
$\endgroup$
1
  • 2
    $\begingroup$ From the help :"Sound[{SoundNote["C", {0, 0.3}], SoundNote["G", {0.1, 0.5}]}]" this plays 2 overlapping notes. $\endgroup$ Commented Oct 14, 2021 at 8:20

1 Answer 1

4
$\begingroup$

If you have the two lines separately like this, you can use sampled audio to turn each Sound into a waveform. Then you can simply add the two waveforms together to "mix" them.

rh = Sound@MapThread[SoundNote[#1, #2, "Piano"] &, {note1, time1}]
lh = Sound@MapThread[SoundNote[#1, #2, "Piano"] &, 
  {Join[ConstantArray[None, 4], (note1 - 12) /. {None - 12 -> None}], 
     Join[ConstantArray[b, 4], time1]}]

{rhaudio, lhaudio} = PadRight[First@*AudioData /@ {rh, lh}];
(* Note that the two clips are of different lengths;  
   PadRight pads the end of the shorter one with silence *)

Audio[rhaudio + lhaudio]

This yields an audio clip with the left hand coming in one quarter note early. I think the 4s in the definition of the left-hand line should be 6s instead (since this piece is in $\mathbf{\genfrac{}{}{0pt}{1}{3}{4}}$ time and there are 6 eight notes per bar.)

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.