簡體   English   中英

使用 P5.js 創建聲波

[英]Creating a Sound Wave using P5.js

使用 P5.js,我試圖創建一個在 mp3 播放時繪制的視覺效果。 隨着歌曲的進行,會在畫布上繪制一個矩形以說明其振幅。 我在間隔每個矩形時遇到問題。 使用我寫出的代碼,它們會彼此相鄰繪制,但理想情況下我希望它們之間有 1 或 2px。

這是我現在所擁有的:

在此處輸入圖片說明

這就是我想要的:

在此處輸入圖片說明

任何建議將不勝感激! 這是我的代碼:

var song
var button
var amp
var volHistory = []

function preload(){
    song = loadSound("next-to-me.mp3")
}

function setup(){
    createButtons()
    amp = new p5.Amplitude()
}

function togglePlay(){
    if(!song.isPlaying()){
        song.play()
    } else {
        song.pause()
    }
}

//draw is constantly being run
function draw(){
    //styling
    createCanvas(400, 150)
    background(245)
    stroke(0, 109, 203)

    //populate volHistory
    if(song.isPlaying()){
        var vol = amp.getLevel()
        volHistory.push(vol)
    }

    //iterate through volHistory and draw
    beginShape()
    for(var i = 0; i < volHistory.length; i++){
        var y = map(volHistory[i], 0, 1, height/2, true)
        fill(0, 109, 203)
        rect(i, y, 2, y, 25) //(x, y, w, h, radius)
    }
    endShape()

    //moves wavelength 1 index at a time
    if(volHistory.length > width - 10){
        volHistory.splice(0, 1)
    }

    //draw vertical line
    stroke(250, 30, 100)
    line(volHistory.length, 0, volHistory.length, height)
}

function loaded(){
    createButtons()
}

function createButtons(){
    button = createButton("<img style='width: 50px' src='http://www.stickpng.com/assets/images/580b57fcd9996e24bc43c4f9.png'/>")
    button.mousePressed(togglePlay)
    button.position(162, 50)
    button.style("background-color", color(0,0,0,0))
    button.style("border", 0)
}

要在振幅條之間留出空間,您可以為每個條的 x 位置添加偏移量。 要根據振幅使條形的高度發生變化,您可以將每個矩形的高度設置為映射的振幅,然后通過計算其 y 位置將其居中。

使用偏移量,您的draw函數將如下所示:

function draw(){
    background(245)
    stroke(0, 109, 203)

    //populate volHistory
    if(song.isPlaying()){
        var vol = amp.getLevel()
        volHistory.push(vol)
    }

    //iterate through volHistory and draw
  fill(0, 109, 203)
  var barWidth = 2;
  var offsetWidth = 5;
  var offset = 5;
    for(var i = 0; i < volHistory.length; i++){
        var barHeight = map(volHistory[i], 0, 1, 1, height)
        rect(i + offset, (height/2.0) - (barHeight/2.0), barWidth, barHeight);
        offset += offsetWidth;
    }

    //moves wavelength 1 index at a time and account for bar width and offset width
    if(volHistory.length * (offsetWidth + barWidth) > width - 10){
        volHistory.splice(0, 1)
    }

    //draw vertical line
    stroke(250, 30, 100)
    line(volHistory.length + offset, 0, volHistory.length + offset, height)
}

請注意,在此繪制中createCanvas已移至setup

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM