Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add TriangleWaveGenerator #26

Merged
merged 1 commit into from
Jul 12, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ import androidx.appcompat.app.AppCompatActivity
import com.github.nisrulz.samplezentone.databinding.ActivityMainBinding
import com.github.nisrulz.zentone.MIN_FREQUENCY
import com.github.nisrulz.zentone.ZenTone
import com.github.nisrulz.zentone.wave_generators.SineWaveGenerator
import com.github.nisrulz.zentone.wave_generators.TriangleWaveGenerator

class MainActivity : AppCompatActivity() {

Expand Down Expand Up @@ -117,7 +117,7 @@ class MainActivity : AppCompatActivity() {
zenTone.play(
frequency = freq,
volume = volume,
waveByteArrayGenerator = SineWaveGenerator
waveByteArrayGenerator = TriangleWaveGenerator
)
myFAB.setImageResource(R.drawable.stop)
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package com.github.nisrulz.zentone.wave_generators

import kotlin.math.asin
import kotlin.math.sin

/**
* Triangle wave generator
*
* Triangle Wave: Defined as the arc sine function of a sinusoid
*
* @see <a
* href="https://en.wikipedia.org/wiki/Triangle_wave">Wikipedia</a>
*/
object TriangleWaveGenerator : WaveByteArrayGenerator {

override fun calculateData(index: Int, samplingInterval: Float, amplitude: Int): Byte {
val angle: Double = (Math.PI * index) / samplingInterval
return (amplitude * waveFunction(angle) * Byte.MAX_VALUE).toInt().toByte()
}

private fun waveFunction(angle: Double): Double = asin(sin(angle))
}