// 音符生成器 - 将CA行状态转换为音频波形
module note_generator #(
    parameter SAMPLE_RATE = 48000,
    parameter BIT_DEPTH = 16
)(
    input  wire             clk,
    input  wire             rst_n,
    input  wire [6:0]       midi_note,
    input  wire [6:0]       velocity,
    input  wire             note_on,
    output wire signed [BIT_DEPTH-1:0] audio_out
);
    // 相位累加器（DDS式合成）
    reg [31:0] phase_acc;
    reg [31:0] phase_inc;
    
    // MIDI音符 → 频率 → 相位增量
    // f = 440 * 2^((note-69)/12)
    // phase_inc = f * 2^32 / SAMPLE_RATE
    always @(*) begin
        case (midi_note)
            7'd60: phase_inc = 32'd1594432;   // C4 (261.6Hz)
            7'd62: phase_inc = 32'd1789587;   // D4
            7'd64: phase_inc = 32'd2007542;   // E4
            7'd65: phase_inc = 32'd2129428;   // F4
            7'd67: phase_inc = 32'd2390408;   // G4
            7'd69: phase_inc = 32'd2683378;   // A4 (440Hz)
            7'd71: phase_inc = 32'd3012212;   // B4
            7'd72: phase_inc = 32'd3188864;   // C5
            default: phase_inc = 32'd0;
        endcase
    end
    
    always @(posedge clk or negedge rst_n) begin
        if (!rst_n)
            phase_acc <= 32'd0;
        else if (note_on)
            phase_acc <= phase_acc + phase_inc;
        else
            phase_acc <= 32'd0;
    end
    
    // 正弦波查表（简化：用方波近似）
    assign audio_out = note_on ? 
        (phase_acc[31] ? {1'b0, {(BIT_DEPTH-1){1'b1}}} : {1'b1, {(BIT_DEPTH-1){1'b0}}}) :
        {BIT_DEPTH{1'b0}};
endmodule