首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >根据一首歌的和弦来确定它的音调

根据一首歌的和弦来确定它的音调
EN

Stack Overflow用户
提问于 2017-07-30 10:57:44
回答 8查看 4.4K关注 0票数 42

我如何通过了解歌曲的和弦序列来编程找到歌曲的关键?

我问一些人如何确定歌曲的音调,他们都说他们是通过“耳朵”或“试错”来做的,并且告诉他们和弦是否能解决一首歌.对于普通的音乐家来说,这可能很好,但作为一个程序员,这并不是我想要的答案。

因此,我开始寻找与音乐相关的库,看看是否还有其他人已经为此编写了算法。但是,虽然我在GitHub:https://danigb.github.io/tonal/api/index.html上找到了一个很大的叫做'tonal‘的库,但是我还是找不到一个方法可以接受一个和弦数组并返回键。

我选择的语言将是JavaScript (NodeJs),但我并不一定要寻找JavaScript的答案。伪代码或能被翻译成代码的解释没有太大的麻烦,这是完全正确的。

正如你们中的一些人正确地提到的,歌曲中的键可能会改变。我不确定是否能够可靠地检测到密钥的更改。所以,现在,我只想说,我在寻找一种算法,对给定的和弦序列的键进行很好的近似。

..。在查看了五分之五的圆圈之后,我想我找到了一种模式,可以找到所有属于每个键的和弦。我为此编写了一个函数getChordsFromKey(key)。通过检查每个键的和弦序列的和弦,我可以创建一个数组,其中包含了键与给定的和弦序列匹配的概率:calculateKeyProbabilities(chordSequence)。然后我添加了另一个函数estimateKey(chordSequence),它以最高概率得分的键,然后检查和弦序列的最后一个和弦是否是其中之一。如果是这样的话,它会返回一个只包含那个和弦的数组,否则它会返回一个概率最高的所有和弦的数组。这做了一个好的工作,但它仍然找不到正确的键为许多歌曲或返回多个键的概率相等。主要的问题是和弦,如A5, Asus2, A+, A°, A7sus4, Am7b5, Aadd9, Adim, C/G等,它们不在五分之五的范围内。例如,键C包含与Am键完全相同的和弦,G包含与Em完全相同的和弦,等等。

这是我的代码:

代码语言:javascript
复制
'use strict'
const normalizeMap = {
    "Cb":"B",  "Db":"C#",  "Eb":"D#", "Fb":"E",  "Gb":"F#", "Ab":"G#", "Bb":"A#",  "E#":"F",  "B#":"C",
    "Cbm":"Bm","Dbm":"C#m","Eb":"D#m","Fbm":"Em","Gb":"F#m","Ab":"G#m","Bbm":"A#m","E#m":"Fm","B#m":"Cm"
}
const circleOfFifths = {
    majors: ['C', 'G', 'D', 'A',  'E',  'B',  'F#', 'C#', 'G#','D#','A#','F'],
    minors: ['Am','Em','Bm','F#m','C#m','G#m','D#m','A#m','Fm','Cm','Gm','Dm']
}

function estimateKey(chordSequence) {
    let keyProbabilities = calculateKeyProbabilities(chordSequence)
    let maxProbability = Math.max(...Object.keys(keyProbabilities).map(k=>keyProbabilities[k]))
    let mostLikelyKeys = Object.keys(keyProbabilities).filter(k=>keyProbabilities[k]===maxProbability)

    let lastChord = chordSequence[chordSequence.length-1]

    if (mostLikelyKeys.includes(lastChord))
         mostLikelyKeys = [lastChord]
    return mostLikelyKeys
}

function calculateKeyProbabilities(chordSequence) {
    const usedChords = [ ...new Set(chordSequence) ] // filter out duplicates
    let keyProbabilities = []
    const keyList = circleOfFifths.majors.concat(circleOfFifths.minors)
    keyList.forEach(key=>{
        const chords = getChordsFromKey(key)
        let matchCount = 0
        //usedChords.forEach(usedChord=>{
        //    if (chords.includes(usedChord))
        //        matchCount++
        //})
        chords.forEach(chord=>{
            if (usedChords.includes(chord))
                matchCount++
        })
        keyProbabilities[key] = matchCount / usedChords.length
    })
    return keyProbabilities
}

function getChordsFromKey(key) {
    key = normalizeMap[key] || key
    const keyPos = circleOfFifths.majors.includes(key) ? circleOfFifths.majors.indexOf(key) : circleOfFifths.minors.indexOf(key)
    let chordPositions = [keyPos, keyPos-1, keyPos+1]
    // since it's the CIRCLE of fifths we have to remap the positions if they are outside of the array
    chordPositions = chordPositions.map(pos=>{
        if (pos > 11)
            return pos-12
        else if (pos < 0)
            return pos+12
        else
            return pos
    })
    let chords = []
    chordPositions.forEach(pos=>{
        chords.push(circleOfFifths.majors[pos])
        chords.push(circleOfFifths.minors[pos])
    })
    return chords
}

// TEST

//console.log(getChordsFromKey('C'))
const chordSequence = ['Em','G','D','C','Em','G','D','Am','Em','G','D','C','Am','Bm','C','Am','Bm','C','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Am','Am','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em','Em','C','D','Em']

const key = estimateKey(chordSequence)
console.log('Example chord sequence:',JSON.stringify(chordSequence))
console.log('Estimated key:',JSON.stringify(key)) // Output: [ 'Em' ]

EN

回答 8

Stack Overflow用户

回答已采纳

发布于 2018-03-09 21:15:16

一种方法是找到正在播放的所有音符,并与不同音阶的签名进行比较,看哪一个是最佳匹配。

通常,比例签名是非常独特的。一个自然的小音阶和一个大音阶有相同的音符(对所有的模式都是这样),但一般来说,当我们说小音阶时,我们指的是具有特定特征的和声小音阶。

因此,用不同的音阶来比较和弦中的音符会给你一个很好的估计。你也可以通过给不同的音符增加一些重音(例如,出现最多的音符,或第一个和弦和最后一个和弦,每个和弦的主音等等)来进行精炼。

这似乎能在一定程度上准确地处理大多数基本案例:

代码语言:javascript
复制
'use strict'
const allnotes = [
  "C", "C#", "D", "Eb", "E", "F", "F#", "G", "Ab", "A", "Bb", "B"
]

// you define the scales you want to validate for, with name and intervals
const scales = [{
  name: 'major',
  int: [2, 4, 5, 7, 9, 11]
}, {
  name: 'minor',
  int: [2, 3, 5, 7, 8, 11]
}];

// you define which chord you accept. This is easily extensible,
// only limitation is you need to have a unique regexp, so
// there's not confusion.

const chordsDef = {
  major: {
    intervals: [4, 7],
    reg: /^[A-G]$|[A-G](?=[#b])/
  },
  minor: {
    intervals: [3, 7],
    reg: /^[A-G][#b]?[m]/
  },
  dom7: {
    intervals: [4, 7, 10],
    reg: /^[A-G][#b]?[7]/
  }
}

var notesArray = [];

// just a helper function to handle looping all notes array
function convertIndex(index) {
  return index < 12 ? index : index - 12;
}


// here you find the type of chord from your 
// chord string, based on each regexp signature
function getNotesFromChords(chordString) {

  var curChord, noteIndex;
  for (let chord in chordsDef) {
    if (chordsDef[chord].reg.test(chordString)) {
      var chordType = chordsDef[chord];
      break;
    }
  }

  noteIndex = allnotes.indexOf(chordString.match(/^[A-G][#b]?/)[0]);
  addNotesFromChord(notesArray, noteIndex, chordType)

}

// then you add the notes from the chord to your array
// this is based on the interval signature of each chord.
// By adding definitions to chordsDef, you can handle as
// many chords as you want, as long as they have a unique regexp signature
function addNotesFromChord(arr, noteIndex, chordType) {

  if (notesArray.indexOf(allnotes[convertIndex(noteIndex)]) == -1) {
    notesArray.push(allnotes[convertIndex(noteIndex)])
  }
  chordType.intervals.forEach(function(int) {

    if (notesArray.indexOf(allnotes[noteIndex + int]) == -1) {
      notesArray.push(allnotes[convertIndex(noteIndex + int)])
    }

  });

}

// once your array is populated you check each scale
// and match the notes in your array to each,
// giving scores depending on the number of matches.
// This one doesn't penalize for notes in the array that are
// not in the scale, this could maybe improve a bit.
// Also there's no weight, no a note appearing only once
// will have the same weight as a note that is recurrent. 
// This could easily be tweaked to get more accuracy.
function compareScalesAndNotes(notesArray) {
  var bestGuess = [{
    score: 0
  }];
  allnotes.forEach(function(note, i) {
    scales.forEach(function(scale) {
      var score = 0;
      score += notesArray.indexOf(note) != -1 ? 1 : 0;
      scale.int.forEach(function(noteInt) {
        // console.log(allnotes[convertIndex(noteInt + i)], scale)

        score += notesArray.indexOf(allnotes[convertIndex(noteInt + i)]) != -1 ? 1 : 0;

      });

      // you always keep the highest score (or scores)
      if (bestGuess[0].score < score) {

        bestGuess = [{
          score: score,
          key: note,
          type: scale.name
        }];
      } else if (bestGuess[0].score == score) {
        bestGuess.push({
          score: score,
          key: note,
          type: scale.name
        })
      }



    })
  })
  return bestGuess;

}


document.getElementById('showguess').addEventListener('click', function(e) {
  notesArray = [];
  var chords = document.getElementById('chodseq').value.replace(/ /g,'').replace(/["']/g,'').split(',');
  chords.forEach(function(chord) {
    getNotesFromChords(chord)
  });
  var guesses = compareScalesAndNotes(notesArray);
  var alertText = "Probable key is:";
  guesses.forEach(function(guess, i) {
    alertText += (i > 0 ? " or " : " ") + guess.key + ' ' + guess.type;
  });
  
  alert(alertText)
  
})
代码语言:javascript
复制
<input type="text" id="chodseq" />

<button id="showguess">
Click to guess the key
</button>

对于你的例子,它给G大调,那是因为一个和声小尺度,没有D大调或Bm和弦。

你可以试试简单的: C,F,G或Eb,Fm,Gm

或者一些事故: C,D7,G7 (这一次会给你两个猜测,因为有一个真正的模糊,没有提供更多的信息,它可能是两者兼而有之)

有事故但准确的: C,Dm,G,A

票数 7
EN

Stack Overflow用户

发布于 2017-07-30 11:03:09

一首歌中的和弦主要是琴键的音阶。我想,如果有足够的数据,您可以在统计上得到一个很好的近似,方法是将列出的和弦中的主要意外情况与键的键签名进行比较。

请参阅五分之五

当然,任何键中的歌曲都会出现意外,而不是键级,因此很可能是一个统计近似。但是在几个条子上,如果你把意外事件加起来,过滤掉除最常见的事故外,你可能能够匹配一个密钥签名。

增编:正如Jonas w正确指出的那样,您可能能够获得签名,但是您不太可能确定它是一个主要的还是次要的密钥。

票数 14
EN

Stack Overflow用户

发布于 2017-09-26 14:31:55

这是我想出来的。现代JS仍然是新的,所以对于map()的混乱和错误使用表示歉意。

我查看了tonal库的内部结构,它有一个函数scales.detect(),但是它没有好处,因为它需要所有的注释。相反,我使用它作为灵感,并将其简化为一个简单的便笺列表,并将其作为所有可能尺度的子集在所有转换中进行检查。

代码语言:javascript
复制
const _ = require('lodash');
const chord = require('tonal-chord');
const note = require('tonal-note');
const pcset = require('tonal-pcset');
const dictionary = require('tonal-dictionary');
const SCALES = require('tonal-scale/scales.json');
const dict = dictionary.dictionary(SCALES, function (str) { return str.split(' '); });

//dict is a dictionary of scales defined as intervals
//notes is a string of tonal notes eg 'c d eb'
//onlyMajorMinor if true restricts to the most common scales as the tonal dict has many rare ones
function keyDetect(dict, notes, onlyMajorMinor) {
    //create an array of pairs of chromas (see tonal docs) and scale names
    var chromaArray = dict.keys(false).map(function(e) { return [pcset.chroma(dict.get(e)), e]; });
    //filter only Major/Minor if requested
    if (onlyMajorMinor) { chromaArray = chromaArray.filter(function (e) { return e[1] === 'major' || e[1] === 'harmonic minor'; }); }
 //sets is an array of pitch classes transposed into every possibility with equivalent intervals
 var sets = pcset.modes(notes, false);

 //this block, for each scale, checks if any of 'sets' is a subset of any scale
 return chromaArray.reduce(function(acc, keyChroma) {
    sets.map(function(set, i) {
        if (pcset.isSubset(keyChroma[0], set)) {
            //the midi bit is a bit of a hack, i couldnt find how to turn an int from 0-11 into the repective note name. so i used the midi number where 60 is middle c
            //since the index corresponds to the transposition from 0-11 where c=0, it gives the tonic note of the key
            acc.push(note.pc(note.fromMidi(60+i)) + ' ' + keyChroma[1]);
            }
        });
        return acc;
    }, []);

    }

const p1 = [ chord.get('m','Bb'), chord.get('m', 'C'), chord.get('M', 'Eb') ];
const p2 = [ chord.get('M','F#'), chord.get('dim', 'B#'), chord.get('M', 'G#') ];
const p3 = [ chord.get('M','C'), chord.get('M','F') ];
const progressions = [ p1, p2, p3 ];

//turn the progression into a flat string of notes seperated by spaces
const notes = progressions.map(function(e) { return _.chain(e).flatten().uniq().value(); });
const possibleKeys = notes.map(function(e) { return keyDetect(dict, e, true); });

console.log(possibleKeys);
//[ [ 'Ab major' ], [ 'Db major' ], [ 'C major', 'F major' ] ]

一些缺点:

  • 并不能给出你想要的和谐音符。在p2中,更正确的响应是C#专业,但是可以通过检查原始进度来解决这个问题。 -‎将不会处理与和弦无关的“装饰”,这可能发生在流行歌曲中,例如。CMaj7 FMaj7 GMaj7而不是C,我不确定这有多普遍,我想也不是太多。
票数 11
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45399081

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档