Preface:

For music rhythm games, notes need to be generated according to the rhythm. Cococs own API can not meet the needs, so you need to develop your own.Copy the code

Functions and ideas:

Parsing – Audio to write the peak capture of.mp3 in the audio directory of this project to the.json file, which is easy to read and use in the game.

Rely on Python librosa library to analyze audio, write cocos extension plug-in, achieve one-click peak generation. Json file.

Key code:

main.py

#coding=utf-8
import librosa
import os
import json
import numpy as np


def save_data(data) :
    Go to resources
    path = os.path.abspath('.. /.. ') + '/assets/resources'
    os.chdir( path )
    f=open("level.json"."w")
    f.write(json.dumps(data))
    f.close()

def analysis(nameKey,path,configJosn) :
    y, sr = librosa.load(path)
    tempo, beat_frames = librosa.beat.beat_track(y=y, sr=sr)

    # Get music time
    musicTimer=librosa.get_duration(filename=path)
    # Convert time to frames
    musicFrame=librosa.time_to_frames(musicTimer)
    The beat of each song is roughly fixed
    beatsDis=musicFrame/len(beat_frames)

    # Peak point frames
    onset_env = librosa.onset.onset_strength(y=y, sr=sr,hop_length=512,aggregate=np.median)
    peaks = librosa.util.peak_pick(onset_env, 3.3.3.5.0.5.12)
    peaks_to_timer= librosa.frames_to_time(peaks, sr=sr)

    dataStr="[0,"
    for item in peaks_to_timer:
            dataStr=dataStr+str(item)+","
    dataStr=dataStr[:len(dataStr)-1]
    dataStr=dataStr+"]"

    json={}
    json["timer"]=musicTimer
    json["rhythm"]=dataStr
    configJosn[nameKey]=json

def getFileList(configJosn) :
    # specify directory
    basePath = os.path.abspath('.. /.. ') + '/assets/audio'
    audioList = os.listdir(basePath)
    print(audioList)

    for tmp in audioList:
            audioPath = os.path.join(basePath, tmp)
            if audioPath.endswith('.mp3'):
                    name=tmp[:tmp.find('.mp3')]
                    print("print "+audioPath+" audio datas----")
                    analysis(name,audioPath,configJosn)

if __name__=="__main__":
	configJosn={}
	getFileList(configJosn)
	save_data(configJosn)
Copy the code

The main js file

"use strict";
// Import the command line
const exec = require("child_process").exec; 
module.exports = {
  messages: {
    open() {
      var cmdStr = "python main.py";
      Editor.log("Generating rhythm...")
      exec(cmdStr, {cwd: __dirname},function (err, stdout, stderr) {
        if (err) {
          Editor.log("error:" + stderr);
        } else {
          Editor.log("Musical rhythm generation."+ stdout); }}); ,}}};/ / exec0 (CMD command to be executed, {CWD: "working directory"}, (error, stdout, stderr) = > {})
Copy the code