4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

Typescript + viteでworker/AudioWorkletProcessorつくるならimport suffixつけるだけ!

Last updated at Posted at 2024-08-06

TD; LR;

suffixつけるだけでworkerもurlなtsもちゃんとトランスパイルしてくれるよ、よかったね、という話です

ちょっとだけ詳細

workerやWorkletのように外部のjsを読みこむ必要があるコードを実装する必要がある場合、そのファイルをどう生成するのかがちょっとした課題になることがあります
rawなjsを書くなり、buildの設定でoutputを追加してあげればいいのですが、viteではimportにparameterを追加することで、そういった生成をうけもってくれます

読め

https://ja.vitejs.dev/guide/features#%E3%82%AF%E3%82%A8%E3%83%AA%E3%83%BC%E3%82%B5%E3%83%95%E3%82%A3%E3%83%83%E3%82%AF%E3%82%B9%E3%81%AB%E3%82%88%E3%82%8B%E3%82%A4%E3%83%B3%E3%83%9B%E3%82%9A%E3%83%BC%E3%83%88
ちゃんとドキュンメントあるからね!

サンプル

import Worker from './worker.ts?worker'
import workletURL from './MyAudioProcessor.ts?url'
const setupAudioWorklet = async() => {
    const userMedia = await navigator.mediaDevices.getUserMedia({audio:true, video: false})    
    const audioContext = new AudioContext()
    audioContext.resume()
    const microphone =await audioContext.createMediaStreamSource(userMedia)
    await audioContext.audioWorklet.addModule(workletURL)
    const audioNode = new AudioWorkletNode(
      audioContext,
      'MyAudioProcessor'
    )
    microphone.connect(audioNode).connect(audioContext.destination)
 
}

const setupWorker = () => {
    const worker = new Worker();
    worker.postMessage({data: 'hello'})

}
const main = async() => {
    setupAudioWorklet()
    setupWorker()
}
document.addEventListener('DOMContentLoaded', () => {
    const button = document.querySelector('#button') as HTMLButtonElement
    button.addEventListener('click', async() => {
        main()
    })
}) 

https://github.com/generosennin/worker-sample
完全なコードはこちら

まとめ

build設定をじらず、workerやWorkletのjsをトランスパイルする方法でした

4
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?