Scala - Playing a Sound -Beeping

1.2k views Asked by At

I am tryig to do something in order that to have a beep or sound for 2-3 minutes when a proces is done in my app. Currently I have this:

object SoundPlay {
import scala.collection.mutable.ListBuffer
val bb = new ListBuffer[Any]

def main(args: Array[String]) {

   val beep = java.awt.Toolkit.getDefaultToolkit.beep
   for (i <- 1 to 100) {
     bb += beep
   }

   bb.foreach(println(_))

  }
}

but this one makes only one sound and I can't make it repeated moe than Once.?!

My UPDATE

I wrote this and is a kind of:

object SoundPlay {
def main(args: Array[String]) {
   for(i <- 1 to 10) {
     Thread.sleep(1000)
     java.awt.Toolkit.getDefaultToolkit.beep()
    }
  }
 }
2

There are 2 answers

1
lmm On BEST ANSWER

beep is a nasty side-effecting method. If you want to repeat it you'll have to capture it via something like scalaz Task:

import scalaz._, Scalaz._, concurrent.Task

val beepTask = Task(java.awt.Toolkit.getDefaultToolkit.beep)
//traverse so we gather the 100 Tasks into a single Task
val bb = (1 to 100).toList traverse {_ => beepTask}
//everything is "lazy" until we call run, that's when the beeps actually happen
bb.run
1
pagoda_5b On

You're adding to the Buffer the result of calling beep (which is void). This means that the beep is made once as a side-effect and the void result is stored in the variable.

Probably you want to define an action that calls beep using a lambda expression or (as in the following code) partially applying the beep function.

object SoundPlay {
  import scala.collection.mutable.ListBuffer
  import java.awt.Toolkit._

  val bb = ListBuffer[() => Unit]() //a buffer of functions

  def main(args: Array[String]) {

    val beep = getDefaultToolkit.beep _ //this is a function with no arg
    for (i <- 1 to 100) {
      bb += beep
    }

    bb.foreach { case b =>
      println(b())
      Thread.sleep(500) // This pause is to hear the separate beeps
    }   

  }
}