Thursday, 2 June 2022

Utility function to toggle ARIA and data attributes, and manage CSS classes on HTML dropdowns

I have a dropdown utility function that is mostly working. The issues are with properly handling the toggling of the data-text and aria attributes for the buttons when clicking on the non-target button or outside the target element completely.

I have included my window.addEventListener code, but have commented it out as it is affecting the display of the ul sub menu elements.

I am learning vanilla JavaScript in bits and pieces, so please provide tips and solutions that are simple for a novice JS developer. Thanks.

const navUtility = (() => {
  const buttons = document.querySelectorAll("[data-nav-toggle]");
  const containers = document.querySelectorAll("[data-nav-container]");

  if (!buttons) {
    return;
  }

  function dropdownToggleHandler() {
    buttons.forEach((button) => {
      button.addEventListener("click", toggleContainer);
    });
  }

  function toggleContainer(e) {
    toggleButtonClass(e.target);
    toggleButtonAria(e.target);
    toggleButtonDataText(e.target);
    toggleContainers(e.target);
  }

  function toggleButtonClass(button) {
    if (button.classList.contains("is-active")) {
      button.classList.remove("is-active");
    } else {
      button.classList.add("is-active");
    }
  }

  function toggleButtonAria(button) {
    const expandedValue = button.getAttribute("aria-expanded");
    const setValue = expandedValue === "true" ? "false" : "true";
    button.setAttribute("aria-expanded", setValue);
  }

  function toggleButtonDataText(button) {
    const originalValue = button.getAttribute("data-text-original");
    const swapValue = button.getAttribute("data-text-swap");
    if (swapValue === button.textContent) {
      button.textContent = button.getAttribute("data-text-original");
    } else {
      button.setAttribute("data-text-original", button.textContent);
      button.textContent = button.getAttribute("data-text-swap");
    }
  }

  function toggleContainers(button) {
    const parent = button.closest("[data-nav-container]");
    parent.classList.toggle("is-expanded");
    document.querySelectorAll(".is-expanded").forEach(function(parentExpanded) {
      if (parentExpanded !== parent) {
        parentExpanded.classList.remove("is-expanded");
      }
    });
  }

  dropdownToggleHandler();

  /* window.addEventListener('click', function(e) {
    containers.forEach((container) => {
      if (e.target !== container) {
        container.classList.remove("is-expanded");
      }
    });
  }); */
})();
nav {
  position: relative;
}

nav>ul {
  width: 21rem;
  max-height: 0;
  position: absolute;
  right: auto;
  left: 0;
  z-index: 5;
  visibility: hidden;
  background-color: grey;
  transition: max-height 200ms ease-out;
}

nav.is-expanded>ul {
  max-height: 4000px;
  visibility: visible;
}
<nav class="" data-nav-container="want-to-navigation" aria-label="Site tools navigation">
  <button aria-expanded="false" class="" data-nav-toggle="want-to-navigation" data-text-swap="Close" data-text-original="I Want To...">Close</button>
  <ul id="want-to-navigation" class="menu">
    <li>
      <a>Apply For</a>
      <ul class="sub-menu">
        <li>
          <a href="#">Development Permits</a>
        </li>
        <li>
          <a href="#">Dust Suppressant</a>
        </li>
        <li>
          <a href="#">Fire Permit</a>
        </li>
        <li>
          <a href="#">Employment</a>
        </li>
        <li>
          <a href="#">Subdivision</a>
        </li>
      </ul>
    </li>
  </ul>
</nav>
<nav class="" data-nav-container="quick-links-navigation" aria-label="Site quick links navigation">
  <button aria-expanded="false" class="" data-nav-toggle="quick-links-navigation" data-text-swap="Close" data-text-original="Quicklinks">Close</button>
  <ul id="quick-links-navigation">
    <li>
      <a href="#">Community Guide</a>
    </li>
    <li>
      <a href="#">Notice of Development</a>
    </li>
    <li>
      <a href="#">Workshops &amp; Courses</a>
    </li>
    <li>
      <a href="#">Council Business</a>
    </li>
  </ul>
</nav>


from Utility function to toggle ARIA and data attributes, and manage CSS classes on HTML dropdowns

Android AudioTrack.onPlaybackPositionUpdateListener not always firing on time

I have noticed that AudioTrack.setPlaybackPositionUpdateListener() sometimes does not seem to work as intended (at least in Android Studio emulators from API 19-22).

I've made a little test program that has a button that when pressed, starts feeding an AudioTrack with one-second-long buffers of audio.

The AudioTrack is supposed to call back using onPeriodicNotification() which in turn flips the background color of the Activity and makes a Log.

Expected behavior:

The notification is sent and received more-or-less exactly every one second after having pressed the start button.

This does happen most of the time, but sometimes (seems to be mostly on API 19-22):

The first (after one-second) notification is missed/postponed, and instead we get two simultaneous notifications happening at two seconds.

Why is this happening? Is there a better way to get a callback based on the playback head position?

The only reason I can think of is possibly a CPU frequency scaling issue as described around the 19:30 mark of this video.

MainActivity:

public class MainActivity extends Activity {

    View rootView;
    Button startButton;
    int initialBackgroundColor;
    boolean colorFlipper = false;
    boolean isPlaying = false;

    // AUDIO -------------
    AudioTrack audioTrack;
    int sampleRateInHz = 44100;
    int bufferSizeInBytes = 44100;
    byte[] silenceArray;

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        rootView = findViewById(R.id.rootView);
        startButton = findViewById(R.id.startButton);
        initialBackgroundColor = rootView.getDrawingCacheBackgroundColor();

        // AUDIO -------------
        audioTrack = new AudioTrack(AudioManager.STREAM_MUSIC, sampleRateInHz, AudioFormat.CHANNEL_OUT_MONO,
                AudioFormat.ENCODING_PCM_16BIT, bufferSizeInBytes, AudioTrack.MODE_STREAM);
        audioTrack.setPositionNotificationPeriod(44100); // this amounts to one second


        // create "dummy" (silent) sound... one second long
        silenceArray = new byte[bufferSizeInBytes];
        for (int i = 0; i < (bufferSizeInBytes-1); i++)
            silenceArray[i] = 0;

    }

    public void startPressed(View v) {
        boolean wasPlayingWhenPressed = startButton.isSelected();
        startButton.setSelected(!startButton.isSelected());
        if (wasPlayingWhenPressed) {
            stop();
            startButton.setText("START");
        } else {
            start();
            startButton.setText("STOP");
        }
    }

    private void start() {
        isPlaying = true;
        audioTrack.reloadStaticData();
        audioTrack.play();

        Runnable r = new Runnable() {
            public void run() {

                audioTrack.setPlaybackPositionUpdateListener(new AudioTrack.OnPlaybackPositionUpdateListener(){
                    @Override
                    public void onMarkerReached(AudioTrack arg0) {
                    }
                    @Override
                    public void onPeriodicNotification(AudioTrack arg0) {
                        // this *should* be called every second after play is pressed,
                        // but sometimes the first call is postponed and comes out
                        // simultaneously with the second call
                        Log.i("XXX","onPeriodicNotification() was called");
                        flipBackgroundColor();
                    }
                });

                while(isPlaying) {
                    audioTrack.write(silenceArray,0,silenceArray.length);
                }
            }
        };

        Thread backround_thread = new Thread(r);
        backround_thread.start();
    }

    private void stop() {

        isPlaying = false;
        audioTrack.stop();

    }

    private void flipBackgroundColor(){

        colorFlipper = !colorFlipper;
        if (colorFlipper) {
            rootView.setBackgroundColor(Color.RED);
        } else {
            rootView.setBackgroundColor(initialBackgroundColor);
        }

    }

}

activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rootView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/startButton"
        android:onClick="startPressed"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginEnd="8dp"
        android:layout_marginStart="8dp"
        android:layout_marginTop="8dp"
        android:text="start"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

build.gradle:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 27
    defaultConfig {
        applicationId "com.example.boober.stackqaudiotrackcallback"
        minSdkVersion 19
        targetSdkVersion 27
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support.constraint:constraint-layout:1.1.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
}


from Android AudioTrack.onPlaybackPositionUpdateListener not always firing on time

Wednesday, 1 June 2022

How to get the real and imag arrays for createPeriodicWave for a piecewise periodic function?

The pattern of the wave is as follows:

0.0 - 0.5 => low,
0.5 - 1.0 => high,
1.0 - 2.0 => low,
2.0 - 2.5 => high,
2.5 - 4.0 => low,
4.0 - 4.5 => high,
4.5 - 6.5 => low,
6.5 - 7.0 => high,

enter image description here

The pulses are equal but the time between different pulses increases as follows: 0.5, 1.0, 1.5, 2.0. This pattern repeats itself so that if we keep going the next iteration would look like this:

7.0 - 7.5 => low,
7.5 - 8.0 => high,
8.0 - 9.0 => low,
9.0 - 9.5 => high,
9.5 - 11.0 => low,
11.0 - 11.5 => high,
11.5 - 13.5 => low,
13.5 - 14.0 => high,

enter image description here

I believe the lows should be -1 instead of 0 (not sure though). How can I get the real and imag arrays for this waveform?

https://developer.mozilla.org/en-US/docs/Web/API/BaseAudioContext/createPeriodicWave



from How to get the real and imag arrays for createPeriodicWave for a piecewise periodic function?