Skip to content

Commit

Permalink
feat(10%): Audio
Browse files Browse the repository at this point in the history
  • Loading branch information
sheepbox8646 committed Jul 10, 2024
1 parent d6c6115 commit 542dc22
Show file tree
Hide file tree
Showing 5 changed files with 58 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/scene1.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,4 +13,5 @@ export default nc.createScene(
.on(nc.keyDown, (_, __) => {
console.log('www')
})
.animate(play(await useAudio('./xxx'))/.withAttr({ duration: 1, speed: 2 }))

Check failure on line 16 in examples/scene1.ts

View workflow job for this annotation

GitHub Actions / type-check

Expression expected.
)
16 changes: 16 additions & 0 deletions packages/basic/src/animations/audio/play.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { withHook } from '@newcar/core'
import type { AudioPlayer } from '../../widgets/audio-player'

export function play(audio: ArrayBuffer) {
let source: AudioBufferSourceNode

return withHook<AudioPlayer, {
speed?: number
}>({
before({ widget }) {
source = widget.context.createBufferSource()
source.buffer = audio
},
animate() {},
})
}
14 changes: 14 additions & 0 deletions packages/basic/src/widgets/audio-player.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import type { WidgetOptions, WidgetStyle } from '@newcar/core'
import { Widget } from '@newcar/core'

export interface AudioPlayerOptions extends WidgetOptions {
style?: WidgetStyle
}

export class AudioPlayer extends Widget {
context: AudioContext = new AudioContext()

constructor(options?: AudioPlayerOptions) {
super(options)
}
}
26 changes: 26 additions & 0 deletions packages/core/src/apis/use-audio.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import { $source } from '../global'

/**
* Preloading a font file.
* @param src The font file's path.
* @returns The Font with `ArrayBuffer` type.
*/
export async function useAudio(src: string) {
if (typeof window !== 'undefined') {
const response = await fetch(src)
const array = await response.arrayBuffer()
$source.fonts.push(array)
return array
}
else {
const fs = await import('node:fs')
const path = await import('node:path')
const buffer = fs.readFileSync(path.resolve(src))
const array = buffer.buffer.slice(
buffer.byteOffset,
buffer.byteOffset + buffer.byteLength,
)
$source.fonts.push(array)
return array
}
}
1 change: 1 addition & 0 deletions packages/core/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export * from './event'
export * from './apis/physical'
export * from './apis/use-font'
export * from './apis/use-image'
export * from './apis/use-audio'
export * from './apis/with-hook'
export * from './apis/bind'
export * from './apis/change-many'
Expand Down

0 comments on commit 542dc22

Please sign in to comment.