Yêu cầu thg 9 20, 2023 4:12 SA 67 0 1
  • 67 0 1
+2

Đưa media từ rails assets vào trong file javascript

Chia sẻ
  • 67 0 1

Chào mọi người. Mình lại có câu hỏi

Hiện tại trong code mình đang xử lý như dưới đây.

import { Controller } from '@hotwired/stimulus'

const SOUND = `/assets/audio/drumsticks.mp3`
// const SOUND = `../assets/audio/drumsticks.mp3`

export default class MetronomeController extends Controller {
  static targets = ['bpm', 'tempoButton']

  connect() {
    this.bpm = parseInt(this.bpmTarget.value)
    this.playing = false
    this.tempoButtonTarget.textContent = this.tempoButtonTarget.innerHTML
    this.beat = new Audio(SOUND)
  }

  handleClick() {
    this.playing = !this.playing

    if (this.playing) {
      this.start()
    } else {
      this.stop()
    }
  }

  start() {
    console.log(this.bpm)
    this.timer = setInterval(() => this.beat.play(), (60 / this.bpm) * 1000)
    this.tempoButtonTarget.textContent = 'Stop metronome for the song'
  }

  stop() {
    clearInterval(this.timer)
    this.tempoButtonTarget.textContent = 'Start metronome for the song'
  }
}

File app/assets/audio/drumsticks.mp3 mình đã có. Tuy nhiên hiện phía js của mình đang không đọc được file này. Project Rails của mình có cần config gì thêm không nhỉ?

1 CÂU TRẢ LỜI


Đã trả lời thg 9 21, 2023 5:02 CH
by Dev Success 101
0

File của em đã được public đúng URL chưa? Anh đoán là chưa. Em đưa nó vào thư mục public nhé. http://localhost/assets/audio/drumsticks.mp3

Với cả, em dùng lệnh setInterval với this như kia sẽ lỗi đó. Vì this sẽ out of scope và còn không tồn tại. Em dùng kiểu này:

setInterval(this.beat.play.bind(this.beat), 1000)
Chia sẻ
Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí