Sound[] generates a visual representation of notes. I would like to extract that image, only notes, without controls and borders. How can I do it?

Take this example

Sound[SoundNote @@@ Transpose @ {
  {"E5", "D5", "F#4", "G#4", "C#5", "B4", "D4", "E4", "B4", "A4", "C#4", "E4", "A4"},
  {1/8,  1/8,  1/4,   1/4,   1/8,   1/8,  1/4,  1/4,  1/8,  1/8,  1/4,   1/4,  1/2 }

enter image description here

So far, I found that I can Rasterize the whole output. Also, if I press Ctrl Shift E on the output it seems like there is something, but the code is not simple and very low level. I'm not sure how to translate that into graphics primitives. This method requires manual intervention anyway, and I would like to get the image automatically.


2 Answers 2

FirstCase[ToBoxes[sound], g_GraphicsBox :> 
  First @ Cases[ToExpression[g], Inset[display_, ___] :> display, All]

Also if you dig through the definition, the relevant part is:

{samples, midi} = Sound`NormalizeSound[sound];
sampleRate = Sound`SoundSampleRate[samples];
Sound`SequencePlot[midi, sampleRate]

You need to use ToBoxes then extract the part corresponding to the GraphicsBox with the purple note RectangleBox boxes. This happens to be part [[1,1,2,1,1]] which you can get with a bit of experimentation. Then remove the frame if you don't want that by using a replacement with Nothing. Finally, use ToExpression to convert the result into something visible - which should have a Graphics head:

s = Sound[
     SoundNote @@@ 
      Transpose@{{"E5", "D5", "F#4", "G#4", "C#5", "B4", "D4", "E4", 
         "B4", "A4", "C#4", "E4", "A4"}, {1/8, 1/8, 1/4, 1/4, 1/8, 
         1/8, 1/4, 1/4, 1/8, 1/8, 1/4, 1/4, 1/2}}]

 ToBoxes[s][[1, 1, 2, 1, 1]] /. {Rule[Frame, True] :> Nothing, 
   Rule[FrameStyle, _] :> Nothing}



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.