File size: 60,320 Bytes
4cef980 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""Unit conversion utilities"""
import re
import numpy as np
from . import notation
from ..util.exceptions import ParameterError
from ..util.decorators import deprecate_positional_args
__all__ = [
"frames_to_samples",
"frames_to_time",
"samples_to_frames",
"samples_to_time",
"time_to_samples",
"time_to_frames",
"blocks_to_samples",
"blocks_to_frames",
"blocks_to_time",
"note_to_hz",
"note_to_midi",
"midi_to_hz",
"midi_to_note",
"hz_to_note",
"hz_to_midi",
"hz_to_mel",
"hz_to_octs",
"mel_to_hz",
"octs_to_hz",
"A4_to_tuning",
"tuning_to_A4",
"fft_frequencies",
"cqt_frequencies",
"mel_frequencies",
"tempo_frequencies",
"fourier_tempo_frequencies",
"A_weighting",
"B_weighting",
"C_weighting",
"D_weighting",
"Z_weighting",
"frequency_weighting",
"multi_frequency_weighting",
"samples_like",
"times_like",
"midi_to_svara_h",
"midi_to_svara_c",
"note_to_svara_h",
"note_to_svara_c",
"hz_to_svara_h",
"hz_to_svara_c",
]
@deprecate_positional_args
def frames_to_samples(frames, *, hop_length=512, n_fft=None):
"""Converts frame indices to audio sample indices.
Parameters
----------
frames : number or np.ndarray [shape=(n,)]
frame index or vector of frame indices
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``n_fft // 2``
to counteract windowing effects when using a non-centered STFT.
Returns
-------
times : number or np.ndarray
time (in samples) of each given frame number::
times[i] = frames[i] * hop_length
See Also
--------
frames_to_time : convert frame indices to time values
samples_to_frames : convert sample indices to frame indices
Examples
--------
>>> y, sr = librosa.load(librosa.ex('choice'))
>>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
>>> beat_samples = librosa.frames_to_samples(beats)
"""
offset = 0
if n_fft is not None:
offset = int(n_fft // 2)
return (np.asanyarray(frames) * hop_length + offset).astype(int)
@deprecate_positional_args
def samples_to_frames(samples, *, hop_length=512, n_fft=None):
"""Converts sample indices into STFT frames.
Examples
--------
>>> # Get the frame numbers for every 256 samples
>>> librosa.samples_to_frames(np.arange(0, 22050, 256))
array([ 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6,
7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13,
14, 14, 15, 15, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20,
21, 21, 22, 22, 23, 23, 24, 24, 25, 25, 26, 26, 27, 27,
28, 28, 29, 29, 30, 30, 31, 31, 32, 32, 33, 33, 34, 34,
35, 35, 36, 36, 37, 37, 38, 38, 39, 39, 40, 40, 41, 41,
42, 42, 43])
Parameters
----------
samples : int or np.ndarray [shape=(n,)]
sample index or vector of sample indices
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``- n_fft // 2``
to counteract windowing effects in STFT.
.. note:: This may result in negative frame indices.
Returns
-------
frames : int or np.ndarray [shape=(n,), dtype=int]
Frame numbers corresponding to the given times::
frames[i] = floor( samples[i] / hop_length )
See Also
--------
samples_to_time : convert sample indices to time values
frames_to_samples : convert frame indices to sample indices
"""
offset = 0
if n_fft is not None:
offset = int(n_fft // 2)
samples = np.asanyarray(samples)
return np.floor((samples - offset) // hop_length).astype(int)
@deprecate_positional_args
def frames_to_time(frames, *, sr=22050, hop_length=512, n_fft=None):
"""Converts frame counts to time (seconds).
Parameters
----------
frames : np.ndarray [shape=(n,)]
frame index or vector of frame indices
sr : number > 0 [scalar]
audio sampling rate
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``n_fft // 2``
to counteract windowing effects when using a non-centered STFT.
Returns
-------
times : np.ndarray [shape=(n,)]
time (in seconds) of each given frame number::
times[i] = frames[i] * hop_length / sr
See Also
--------
time_to_frames : convert time values to frame indices
frames_to_samples : convert frame indices to sample indices
Examples
--------
>>> y, sr = librosa.load(librosa.ex('choice'))
>>> tempo, beats = librosa.beat.beat_track(y=y, sr=sr)
>>> beat_times = librosa.frames_to_time(beats, sr=sr)
"""
samples = frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft)
return samples_to_time(samples, sr=sr)
@deprecate_positional_args
def time_to_frames(times, *, sr=22050, hop_length=512, n_fft=None):
"""Converts time stamps into STFT frames.
Parameters
----------
times : np.ndarray [shape=(n,)]
time (in seconds) or vector of time values
sr : number > 0 [scalar]
audio sampling rate
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``- n_fft // 2``
to counteract windowing effects in STFT.
.. note:: This may result in negative frame indices.
Returns
-------
frames : np.ndarray [shape=(n,), dtype=int]
Frame numbers corresponding to the given times::
frames[i] = floor( times[i] * sr / hop_length )
See Also
--------
frames_to_time : convert frame indices to time values
time_to_samples : convert time values to sample indices
Examples
--------
Get the frame numbers for every 100ms
>>> librosa.time_to_frames(np.arange(0, 1, 0.1),
... sr=22050, hop_length=512)
array([ 0, 4, 8, 12, 17, 21, 25, 30, 34, 38])
"""
samples = time_to_samples(times, sr=sr)
return samples_to_frames(samples, hop_length=hop_length, n_fft=n_fft)
@deprecate_positional_args
def time_to_samples(times, *, sr=22050):
"""Convert timestamps (in seconds) to sample indices.
Parameters
----------
times : number or np.ndarray
Time value or array of time values (in seconds)
sr : number > 0
Sampling rate
Returns
-------
samples : int or np.ndarray [shape=times.shape, dtype=int]
Sample indices corresponding to values in ``times``
See Also
--------
time_to_frames : convert time values to frame indices
samples_to_time : convert sample indices to time values
Examples
--------
>>> librosa.time_to_samples(np.arange(0, 1, 0.1), sr=22050)
array([ 0, 2205, 4410, 6615, 8820, 11025, 13230, 15435,
17640, 19845])
"""
return (np.asanyarray(times) * sr).astype(int)
@deprecate_positional_args
def samples_to_time(samples, *, sr=22050):
"""Convert sample indices to time (in seconds).
Parameters
----------
samples : np.ndarray
Sample index or array of sample indices
sr : number > 0
Sampling rate
Returns
-------
times : np.ndarray [shape=samples.shape]
Time values corresponding to ``samples`` (in seconds)
See Also
--------
samples_to_frames : convert sample indices to frame indices
time_to_samples : convert time values to sample indices
Examples
--------
Get timestamps corresponding to every 512 samples
>>> librosa.samples_to_time(np.arange(0, 22050, 512))
array([ 0. , 0.023, 0.046, 0.07 , 0.093, 0.116, 0.139,
0.163, 0.186, 0.209, 0.232, 0.255, 0.279, 0.302,
0.325, 0.348, 0.372, 0.395, 0.418, 0.441, 0.464,
0.488, 0.511, 0.534, 0.557, 0.58 , 0.604, 0.627,
0.65 , 0.673, 0.697, 0.72 , 0.743, 0.766, 0.789,
0.813, 0.836, 0.859, 0.882, 0.906, 0.929, 0.952,
0.975, 0.998])
"""
return np.asanyarray(samples) / float(sr)
@deprecate_positional_args
def blocks_to_frames(blocks, *, block_length):
"""Convert block indices to frame indices
Parameters
----------
blocks : np.ndarray
Block index or array of block indices
block_length : int > 0
The number of frames per block
Returns
-------
frames : np.ndarray [shape=samples.shape, dtype=int]
The index or indices of frames corresponding to the beginning
of each provided block.
See Also
--------
blocks_to_samples
blocks_to_time
Examples
--------
Get frame indices for each block in a stream
>>> filename = librosa.ex('brahms')
>>> sr = librosa.get_samplerate(filename)
>>> stream = librosa.stream(filename, block_length=16,
... frame_length=2048, hop_length=512)
>>> for n, y in enumerate(stream):
... n_frame = librosa.blocks_to_frames(n, block_length=16)
"""
return block_length * np.asanyarray(blocks)
@deprecate_positional_args
def blocks_to_samples(blocks, *, block_length, hop_length):
"""Convert block indices to sample indices
Parameters
----------
blocks : np.ndarray
Block index or array of block indices
block_length : int > 0
The number of frames per block
hop_length : int > 0
The number of samples to advance between frames
Returns
-------
samples : np.ndarray [shape=samples.shape, dtype=int]
The index or indices of samples corresponding to the beginning
of each provided block.
Note that these correspond to the *first* sample index in
each block, and are not frame-centered.
See Also
--------
blocks_to_frames
blocks_to_time
Examples
--------
Get sample indices for each block in a stream
>>> filename = librosa.ex('brahms')
>>> sr = librosa.get_samplerate(filename)
>>> stream = librosa.stream(filename, block_length=16,
... frame_length=2048, hop_length=512)
>>> for n, y in enumerate(stream):
... n_sample = librosa.blocks_to_samples(n, block_length=16,
... hop_length=512)
"""
frames = blocks_to_frames(blocks, block_length=block_length)
return frames_to_samples(frames, hop_length=hop_length)
@deprecate_positional_args
def blocks_to_time(blocks, *, block_length, hop_length, sr):
"""Convert block indices to time (in seconds)
Parameters
----------
blocks : np.ndarray
Block index or array of block indices
block_length : int > 0
The number of frames per block
hop_length : int > 0
The number of samples to advance between frames
sr : int > 0
The sampling rate (samples per second)
Returns
-------
times : np.ndarray [shape=samples.shape]
The time index or indices (in seconds) corresponding to the
beginning of each provided block.
Note that these correspond to the time of the *first* sample
in each block, and are not frame-centered.
See Also
--------
blocks_to_frames
blocks_to_samples
Examples
--------
Get time indices for each block in a stream
>>> filename = librosa.ex('brahms')
>>> sr = librosa.get_samplerate(filename)
>>> stream = librosa.stream(filename, block_length=16,
... frame_length=2048, hop_length=512)
>>> for n, y in enumerate(stream):
... n_time = librosa.blocks_to_time(n, block_length=16,
... hop_length=512, sr=sr)
"""
samples = blocks_to_samples(
blocks, block_length=block_length, hop_length=hop_length
)
return samples_to_time(samples, sr=sr)
def note_to_hz(note, **kwargs):
"""Convert one or more note names to frequency (Hz)
Examples
--------
>>> # Get the frequency of a note
>>> librosa.note_to_hz('C')
array([ 16.352])
>>> # Or multiple notes
>>> librosa.note_to_hz(['A3', 'A4', 'A5'])
array([ 220., 440., 880.])
>>> # Or notes with tuning deviations
>>> librosa.note_to_hz('C2-32', round_midi=False)
array([ 64.209])
Parameters
----------
note : str or iterable of str
One or more note names to convert
**kwargs : additional keyword arguments
Additional parameters to `note_to_midi`
Returns
-------
frequencies : number or np.ndarray [shape=(len(note),)]
Array of frequencies (in Hz) corresponding to ``note``
See Also
--------
midi_to_hz
note_to_midi
hz_to_note
"""
return midi_to_hz(note_to_midi(note, **kwargs))
@deprecate_positional_args
def note_to_midi(note, *, round_midi=True):
"""Convert one or more spelled notes to MIDI number(s).
Notes may be spelled out with optional accidentals or octave numbers.
The leading note name is case-insensitive.
Sharps are indicated with ``#``, flats may be indicated with ``!`` or ``b``.
Parameters
----------
note : str or iterable of str
One or more note names.
round_midi : bool
- If ``True``, allow for fractional midi notes
- Otherwise, round cent deviations to the nearest note
Returns
-------
midi : float or np.array
Midi note numbers corresponding to inputs.
Raises
------
ParameterError
If the input is not in valid note format
See Also
--------
midi_to_note
note_to_hz
Examples
--------
>>> librosa.note_to_midi('C')
12
>>> librosa.note_to_midi('C#3')
49
>>> librosa.note_to_midi('C♯3') # Using Unicode sharp
49
>>> librosa.note_to_midi('C♭3') # Using Unicode flat
47
>>> librosa.note_to_midi('f4')
65
>>> librosa.note_to_midi('Bb-1')
10
>>> librosa.note_to_midi('A!8')
116
>>> librosa.note_to_midi('G𝄪6') # Double-sharp
93
>>> librosa.note_to_midi('B𝄫6') # Double-flat
93
>>> librosa.note_to_midi('C♭𝄫5') # Triple-flats also work
69
>>> # Lists of notes also work
>>> librosa.note_to_midi(['C', 'E', 'G'])
array([12, 16, 19])
"""
if not isinstance(note, str):
return np.array([note_to_midi(n, round_midi=round_midi) for n in note])
pitch_map = {"C": 0, "D": 2, "E": 4, "F": 5, "G": 7, "A": 9, "B": 11}
acc_map = {
"#": 1,
"": 0,
"b": -1,
"!": -1,
"♯": 1,
"𝄪": 2,
"♭": -1,
"𝄫": -2,
"♮": 0,
}
match = re.match(
r"^(?P<note>[A-Ga-g])"
r"(?P<accidental>[#♯𝄪b!♭𝄫♮]*)"
r"(?P<octave>[+-]?\d+)?"
r"(?P<cents>[+-]\d+)?$",
note,
)
if not match:
raise ParameterError("Improper note format: {:s}".format(note))
pitch = match.group("note").upper()
offset = np.sum([acc_map[o] for o in match.group("accidental")])
octave = match.group("octave")
cents = match.group("cents")
if not octave:
octave = 0
else:
octave = int(octave)
if not cents:
cents = 0
else:
cents = int(cents) * 1e-2
note_value = 12 * (octave + 1) + pitch_map[pitch] + offset + cents
if round_midi:
note_value = int(np.round(note_value))
return note_value
@deprecate_positional_args
def midi_to_note(midi, *, octave=True, cents=False, key="C:maj", unicode=True):
"""Convert one or more MIDI numbers to note strings.
MIDI numbers will be rounded to the nearest integer.
Notes will be of the format 'C0', 'C♯0', 'D0', ...
Examples
--------
>>> librosa.midi_to_note(0)
'C-1'
>>> librosa.midi_to_note(37)
'C♯2'
>>> librosa.midi_to_note(37, unicode=False)
'C#2'
>>> librosa.midi_to_note(-2)
'A♯-2'
>>> librosa.midi_to_note(104.7)
'A7'
>>> librosa.midi_to_note(104.7, cents=True)
'A7-30'
>>> librosa.midi_to_note(list(range(12, 24)))
['C0', 'C♯0', 'D0', 'D♯0', 'E0', 'F0', 'F♯0', 'G0', 'G♯0', 'A0', 'A♯0', 'B0']
Use a key signature to resolve enharmonic equivalences
>>> librosa.midi_to_note(range(12, 24), key='F:min')
['C0', 'D♭0', 'D0', 'E♭0', 'E0', 'F0', 'G♭0', 'G0', 'A♭0', 'A0', 'B♭0', 'B0']
Parameters
----------
midi : int or iterable of int
Midi numbers to convert.
octave : bool
If True, include the octave number
cents : bool
If true, cent markers will be appended for fractional notes.
Eg, ``midi_to_note(69.3, cents=True) == 'A4+03'``
key : str
A key signature to use when resolving enharmonic equivalences.
unicode : bool
If ``True`` (default), accidentals will use Unicode notation: ♭ or ♯
If ``False``, accidentals will use ASCII-compatible notation: b or #
Returns
-------
notes : str or iterable of str
Strings describing each midi note.
Raises
------
ParameterError
if ``cents`` is True and ``octave`` is False
See Also
--------
midi_to_hz
note_to_midi
hz_to_note
key_to_notes
"""
if cents and not octave:
raise ParameterError("Cannot encode cents without octave information.")
if not np.isscalar(midi):
return [
midi_to_note(x, octave=octave, cents=cents, key=key, unicode=unicode)
for x in midi
]
note_map = notation.key_to_notes(key=key, unicode=unicode)
note_num = int(np.round(midi))
note_cents = int(100 * np.around(midi - note_num, 2))
note = note_map[note_num % 12]
if octave:
note = "{:s}{:0d}".format(note, int(note_num / 12) - 1)
if cents:
note = "{:s}{:+02d}".format(note, note_cents)
return note
def midi_to_hz(notes):
"""Get the frequency (Hz) of MIDI note(s)
Examples
--------
>>> librosa.midi_to_hz(36)
65.406
>>> librosa.midi_to_hz(np.arange(36, 48))
array([ 65.406, 69.296, 73.416, 77.782, 82.407,
87.307, 92.499, 97.999, 103.826, 110. ,
116.541, 123.471])
Parameters
----------
notes : int or np.ndarray [shape=(n,), dtype=int]
midi number(s) of the note(s)
Returns
-------
frequency : number or np.ndarray [shape=(n,), dtype=float]
frequency (frequencies) of ``notes`` in Hz
See Also
--------
hz_to_midi
note_to_hz
"""
return 440.0 * (2.0 ** ((np.asanyarray(notes) - 69.0) / 12.0))
def hz_to_midi(frequencies):
"""Get MIDI note number(s) for given frequencies
Examples
--------
>>> librosa.hz_to_midi(60)
34.506
>>> librosa.hz_to_midi([110, 220, 440])
array([ 45., 57., 69.])
Parameters
----------
frequencies : float or np.ndarray [shape=(n,), dtype=float]
frequencies to convert
Returns
-------
note_nums : number or np.ndarray [shape=(n,), dtype=float]
MIDI notes to ``frequencies``
See Also
--------
midi_to_hz
note_to_midi
hz_to_note
"""
return 12 * (np.log2(np.asanyarray(frequencies)) - np.log2(440.0)) + 69
def hz_to_note(frequencies, **kwargs):
"""Convert one or more frequencies (in Hz) to the nearest note names.
Parameters
----------
frequencies : float or iterable of float
Input frequencies, specified in Hz
**kwargs : additional keyword arguments
Arguments passed through to `midi_to_note`
Returns
-------
notes : list of str
``notes[i]`` is the closest note name to ``frequency[i]``
(or ``frequency`` if the input is scalar)
See Also
--------
hz_to_midi
midi_to_note
note_to_hz
Examples
--------
Get a single note name for a frequency
>>> librosa.hz_to_note(440.0)
['A5']
Get multiple notes with cent deviation
>>> librosa.hz_to_note([32, 64], cents=True)
['C1-38', 'C2-38']
Get multiple notes, but suppress octave labels
>>> librosa.hz_to_note(440.0 * (2.0 ** np.linspace(0, 1, 12)),
... octave=False)
['A', 'A#', 'B', 'C', 'C#', 'D', 'E', 'F', 'F#', 'G', 'G#', 'A']
"""
return midi_to_note(hz_to_midi(frequencies), **kwargs)
@deprecate_positional_args
def hz_to_mel(frequencies, *, htk=False):
"""Convert Hz to Mels
Examples
--------
>>> librosa.hz_to_mel(60)
0.9
>>> librosa.hz_to_mel([110, 220, 440])
array([ 1.65, 3.3 , 6.6 ])
Parameters
----------
frequencies : number or np.ndarray [shape=(n,)] , float
scalar or array of frequencies
htk : bool
use HTK formula instead of Slaney
Returns
-------
mels : number or np.ndarray [shape=(n,)]
input frequencies in Mels
See Also
--------
mel_to_hz
"""
frequencies = np.asanyarray(frequencies)
if htk:
return 2595.0 * np.log10(1.0 + frequencies / 700.0)
# Fill in the linear part
f_min = 0.0
f_sp = 200.0 / 3
mels = (frequencies - f_min) / f_sp
# Fill in the log-scale part
min_log_hz = 1000.0 # beginning of log region (Hz)
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
logstep = np.log(6.4) / 27.0 # step size for log region
if frequencies.ndim:
# If we have array data, vectorize
log_t = frequencies >= min_log_hz
mels[log_t] = min_log_mel + np.log(frequencies[log_t] / min_log_hz) / logstep
elif frequencies >= min_log_hz:
# If we have scalar data, heck directly
mels = min_log_mel + np.log(frequencies / min_log_hz) / logstep
return mels
@deprecate_positional_args
def mel_to_hz(mels, *, htk=False):
"""Convert mel bin numbers to frequencies
Examples
--------
>>> librosa.mel_to_hz(3)
200.
>>> librosa.mel_to_hz([1,2,3,4,5])
array([ 66.667, 133.333, 200. , 266.667, 333.333])
Parameters
----------
mels : np.ndarray [shape=(n,)], float
mel bins to convert
htk : bool
use HTK formula instead of Slaney
Returns
-------
frequencies : np.ndarray [shape=(n,)]
input mels in Hz
See Also
--------
hz_to_mel
"""
mels = np.asanyarray(mels)
if htk:
return 700.0 * (10.0 ** (mels / 2595.0) - 1.0)
# Fill in the linear scale
f_min = 0.0
f_sp = 200.0 / 3
freqs = f_min + f_sp * mels
# And now the nonlinear scale
min_log_hz = 1000.0 # beginning of log region (Hz)
min_log_mel = (min_log_hz - f_min) / f_sp # same (Mels)
logstep = np.log(6.4) / 27.0 # step size for log region
if mels.ndim:
# If we have vector data, vectorize
log_t = mels >= min_log_mel
freqs[log_t] = min_log_hz * np.exp(logstep * (mels[log_t] - min_log_mel))
elif mels >= min_log_mel:
# If we have scalar data, check directly
freqs = min_log_hz * np.exp(logstep * (mels - min_log_mel))
return freqs
@deprecate_positional_args
def hz_to_octs(frequencies, *, tuning=0.0, bins_per_octave=12):
"""Convert frequencies (Hz) to (fractional) octave numbers.
Examples
--------
>>> librosa.hz_to_octs(440.0)
4.
>>> librosa.hz_to_octs([32, 64, 128, 256])
array([ 0.219, 1.219, 2.219, 3.219])
Parameters
----------
frequencies : number >0 or np.ndarray [shape=(n,)] or float
scalar or vector of frequencies
tuning : float
Tuning deviation from A440 in (fractional) bins per octave.
bins_per_octave : int > 0
Number of bins per octave.
Returns
-------
octaves : number or np.ndarray [shape=(n,)]
octave number for each frequency
See Also
--------
octs_to_hz
"""
A440 = 440.0 * 2.0 ** (tuning / bins_per_octave)
return np.log2(np.asanyarray(frequencies) / (float(A440) / 16))
@deprecate_positional_args
def octs_to_hz(octs, *, tuning=0.0, bins_per_octave=12):
"""Convert octaves numbers to frequencies.
Octaves are counted relative to A.
Examples
--------
>>> librosa.octs_to_hz(1)
55.
>>> librosa.octs_to_hz([-2, -1, 0, 1, 2])
array([ 6.875, 13.75 , 27.5 , 55. , 110. ])
Parameters
----------
octs : np.ndarray [shape=(n,)] or float
octave number for each frequency
tuning : float
Tuning deviation from A440 in (fractional) bins per octave.
bins_per_octave : int > 0
Number of bins per octave.
Returns
-------
frequencies : number or np.ndarray [shape=(n,)]
scalar or vector of frequencies
See Also
--------
hz_to_octs
"""
A440 = 440.0 * 2.0 ** (tuning / bins_per_octave)
return (float(A440) / 16) * (2.0 ** np.asanyarray(octs))
@deprecate_positional_args
def A4_to_tuning(A4, *, bins_per_octave=12):
"""Convert a reference pitch frequency (e.g., ``A4=435``) to a tuning
estimation, in fractions of a bin per octave.
This is useful for determining the tuning deviation relative to
A440 of a given frequency, assuming equal temperament. By default,
12 bins per octave are used.
This method is the inverse of `tuning_to_A4`.
Examples
--------
The base case of this method in which A440 yields 0 tuning offset
from itself.
>>> librosa.A4_to_tuning(440.0)
0.
Convert a non-A440 frequency to a tuning offset relative
to A440 using the default of 12 bins per octave.
>>> librosa.A4_to_tuning(432.0)
-0.318
Convert two reference pitch frequencies to corresponding
tuning estimations at once, but using 24 bins per octave.
>>> librosa.A4_to_tuning([440.0, 444.0], bins_per_octave=24)
array([ 0., 0.313 ])
Parameters
----------
A4 : float or np.ndarray [shape=(n,), dtype=float]
Reference frequency(s) corresponding to A4.
bins_per_octave : int > 0
Number of bins per octave.
Returns
-------
tuning : float or np.ndarray [shape=(n,), dtype=float]
Tuning deviation from A440 in (fractional) bins per octave.
See Also
--------
tuning_to_A4
"""
return bins_per_octave * (np.log2(np.asanyarray(A4)) - np.log2(440.0))
@deprecate_positional_args
def tuning_to_A4(tuning, *, bins_per_octave=12):
"""Convert a tuning deviation (from 0) in fractions of a bin per
octave (e.g., ``tuning=-0.1``) to a reference pitch frequency
relative to A440.
This is useful if you are working in a non-A440 tuning system
to determine the reference pitch frequency given a tuning
offset and assuming equal temperament. By default, 12 bins per
octave are used.
This method is the inverse of `A4_to_tuning`.
Examples
--------
The base case of this method in which a tuning deviation of 0
gets us to our A440 reference pitch.
>>> librosa.tuning_to_A4(0.0)
440.
Convert a nonzero tuning offset to its reference pitch frequency.
>>> librosa.tuning_to_A4(-0.318)
431.992
Convert 3 tuning deviations at once to respective reference
pitch frequencies, using 36 bins per octave.
>>> librosa.tuning_to_A4([0.1, 0.2, -0.1], bins_per_octave=36)
array([ 440.848, 441.698 439.154])
Parameters
----------
tuning : float or np.ndarray [shape=(n,), dtype=float]
Tuning deviation from A440 in fractional bins per octave.
bins_per_octave : int > 0
Number of bins per octave.
Returns
-------
A4 : float or np.ndarray [shape=(n,), dtype=float]
Reference frequency corresponding to A4.
See Also
--------
A4_to_tuning
"""
return 440.0 * 2.0 ** (np.asanyarray(tuning) / bins_per_octave)
@deprecate_positional_args
def fft_frequencies(*, sr=22050, n_fft=2048):
"""Alternative implementation of `np.fft.fftfreq`
Parameters
----------
sr : number > 0 [scalar]
Audio sampling rate
n_fft : int > 0 [scalar]
FFT window size
Returns
-------
freqs : np.ndarray [shape=(1 + n_fft/2,)]
Frequencies ``(0, sr/n_fft, 2*sr/n_fft, ..., sr/2)``
Examples
--------
>>> librosa.fft_frequencies(sr=22050, n_fft=16)
array([ 0. , 1378.125, 2756.25 , 4134.375,
5512.5 , 6890.625, 8268.75 , 9646.875, 11025. ])
"""
return np.fft.rfftfreq(n=n_fft, d=1.0 / sr)
@deprecate_positional_args
def cqt_frequencies(n_bins, *, fmin, bins_per_octave=12, tuning=0.0):
"""Compute the center frequencies of Constant-Q bins.
Examples
--------
>>> # Get the CQT frequencies for 24 notes, starting at C2
>>> librosa.cqt_frequencies(24, fmin=librosa.note_to_hz('C2'))
array([ 65.406, 69.296, 73.416, 77.782, 82.407, 87.307,
92.499, 97.999, 103.826, 110. , 116.541, 123.471,
130.813, 138.591, 146.832, 155.563, 164.814, 174.614,
184.997, 195.998, 207.652, 220. , 233.082, 246.942])
Parameters
----------
n_bins : int > 0 [scalar]
Number of constant-Q bins
fmin : float > 0 [scalar]
Minimum frequency
bins_per_octave : int > 0 [scalar]
Number of bins per octave
tuning : float
Deviation from A440 tuning in fractional bins
Returns
-------
frequencies : np.ndarray [shape=(n_bins,)]
Center frequency for each CQT bin
"""
correction = 2.0 ** (float(tuning) / bins_per_octave)
frequencies = 2.0 ** (np.arange(0, n_bins, dtype=float) / bins_per_octave)
return correction * fmin * frequencies
@deprecate_positional_args
def mel_frequencies(n_mels=128, *, fmin=0.0, fmax=11025.0, htk=False):
"""Compute an array of acoustic frequencies tuned to the mel scale.
The mel scale is a quasi-logarithmic function of acoustic frequency
designed such that perceptually similar pitch intervals (e.g. octaves)
appear equal in width over the full hearing range.
Because the definition of the mel scale is conditioned by a finite number
of subjective psychoaoustical experiments, several implementations coexist
in the audio signal processing literature [#]_. By default, librosa replicates
the behavior of the well-established MATLAB Auditory Toolbox of Slaney [#]_.
According to this default implementation, the conversion from Hertz to mel is
linear below 1 kHz and logarithmic above 1 kHz. Another available implementation
replicates the Hidden Markov Toolkit [#]_ (HTK) according to the following formula::
mel = 2595.0 * np.log10(1.0 + f / 700.0).
The choice of implementation is determined by the ``htk`` keyword argument: setting
``htk=False`` leads to the Auditory toolbox implementation, whereas setting it ``htk=True``
leads to the HTK implementation.
.. [#] Umesh, S., Cohen, L., & Nelson, D. Fitting the mel scale.
In Proc. International Conference on Acoustics, Speech, and Signal Processing
(ICASSP), vol. 1, pp. 217-220, 1998.
.. [#] Slaney, M. Auditory Toolbox: A MATLAB Toolbox for Auditory
Modeling Work. Technical Report, version 2, Interval Research Corporation, 1998.
.. [#] Young, S., Evermann, G., Gales, M., Hain, T., Kershaw, D., Liu, X.,
Moore, G., Odell, J., Ollason, D., Povey, D., Valtchev, V., & Woodland, P.
The HTK book, version 3.4. Cambridge University, March 2009.
See Also
--------
hz_to_mel
mel_to_hz
librosa.feature.melspectrogram
librosa.feature.mfcc
Parameters
----------
n_mels : int > 0 [scalar]
Number of mel bins.
fmin : float >= 0 [scalar]
Minimum frequency (Hz).
fmax : float >= 0 [scalar]
Maximum frequency (Hz).
htk : bool
If True, use HTK formula to convert Hz to mel.
Otherwise (False), use Slaney's Auditory Toolbox.
Returns
-------
bin_frequencies : ndarray [shape=(n_mels,)]
Vector of ``n_mels`` frequencies in Hz which are uniformly spaced on the Mel
axis.
Examples
--------
>>> librosa.mel_frequencies(n_mels=40)
array([ 0. , 85.317, 170.635, 255.952,
341.269, 426.586, 511.904, 597.221,
682.538, 767.855, 853.173, 938.49 ,
1024.856, 1119.114, 1222.042, 1334.436,
1457.167, 1591.187, 1737.532, 1897.337,
2071.84 , 2262.393, 2470.47 , 2697.686,
2945.799, 3216.731, 3512.582, 3835.643,
4188.417, 4573.636, 4994.285, 5453.621,
5955.205, 6502.92 , 7101.009, 7754.107,
8467.272, 9246.028, 10096.408, 11025. ])
"""
# 'Center freqs' of mel bands - uniformly spaced between limits
min_mel = hz_to_mel(fmin, htk=htk)
max_mel = hz_to_mel(fmax, htk=htk)
mels = np.linspace(min_mel, max_mel, n_mels)
return mel_to_hz(mels, htk=htk)
@deprecate_positional_args
def tempo_frequencies(n_bins, *, hop_length=512, sr=22050):
"""Compute the frequencies (in beats per minute) corresponding
to an onset auto-correlation or tempogram matrix.
Parameters
----------
n_bins : int > 0
The number of lag bins
hop_length : int > 0
The number of samples between each bin
sr : number > 0
The audio sampling rate
Returns
-------
bin_frequencies : ndarray [shape=(n_bins,)]
vector of bin frequencies measured in BPM.
.. note:: ``bin_frequencies[0] = +np.inf`` corresponds to 0-lag
Examples
--------
Get the tempo frequencies corresponding to a 384-bin (8-second) tempogram
>>> librosa.tempo_frequencies(384)
array([ inf, 2583.984, 1291.992, ..., 6.782,
6.764, 6.747])
"""
bin_frequencies = np.zeros(int(n_bins), dtype=np.float64)
bin_frequencies[0] = np.inf
bin_frequencies[1:] = 60.0 * sr / (hop_length * np.arange(1.0, n_bins))
return bin_frequencies
@deprecate_positional_args
def fourier_tempo_frequencies(*, sr=22050, win_length=384, hop_length=512):
"""Compute the frequencies (in beats per minute) corresponding
to a Fourier tempogram matrix.
Parameters
----------
sr : number > 0
The audio sampling rate
win_length : int > 0
The number of frames per analysis window
hop_length : int > 0
The number of samples between each bin
Returns
-------
bin_frequencies : ndarray [shape=(win_length // 2 + 1 ,)]
vector of bin frequencies measured in BPM.
Examples
--------
Get the tempo frequencies corresponding to a 384-bin (8-second) tempogram
>>> librosa.fourier_tempo_frequencies(win_length=384)
array([ 0. , 0.117, 0.234, ..., 22.266, 22.383, 22.5 ])
"""
# sr / hop_length gets the frame rate
# multiplying by 60 turns frames / sec into frames / minute
return fft_frequencies(sr=sr * 60 / float(hop_length), n_fft=win_length)
# A-weighting should be capitalized: suppress the naming warning
@deprecate_positional_args
def A_weighting(frequencies, *, min_db=-80.0): # pylint: disable=invalid-name
"""Compute the A-weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
min_db : float [scalar] or None
Clip weights below this threshold.
If `None`, no clipping is performed.
Returns
-------
A_weighting : scalar or np.ndarray [shape=(n,)]
``A_weighting[i]`` is the A-weighting of ``frequencies[i]``
See Also
--------
perceptual_weighting
frequency_weighting
multi_frequency_weighting
B_weighting
C_weighting
D_weighting
Examples
--------
Get the A-weighting for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weights = librosa.A_weighting(freqs)
>>> fig, ax = plt.subplots()
>>> ax.plot(freqs, weights)
>>> ax.set(xlabel='Frequency (Hz)',
... ylabel='Weighting (log10)',
... title='A-Weighting of CQT frequencies')
"""
f_sq = np.asanyarray(frequencies) ** 2.0
const = np.array([12194.217, 20.598997, 107.65265, 737.86223]) ** 2.0
weights = 2.0 + 20.0 * (
np.log10(const[0])
+ 2 * np.log10(f_sq)
- np.log10(f_sq + const[0])
- np.log10(f_sq + const[1])
- 0.5 * np.log10(f_sq + const[2])
- 0.5 * np.log10(f_sq + const[3])
)
return weights if min_db is None else np.maximum(min_db, weights)
@deprecate_positional_args
def B_weighting(frequencies, *, min_db=-80.0): # pylint: disable=invalid-name
"""Compute the B-weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
min_db : float [scalar] or None
Clip weights below this threshold.
If `None`, no clipping is performed.
Returns
-------
B_weighting : scalar or np.ndarray [shape=(n,)]
``B_weighting[i]`` is the B-weighting of ``frequencies[i]``
See Also
--------
perceptual_weighting
frequency_weighting
multi_frequency_weighting
A_weighting
C_weighting
D_weighting
Examples
--------
Get the B-weighting for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weights = librosa.B_weighting(freqs)
>>> fig, ax = plt.subplots()
>>> ax.plot(freqs, weights)
>>> ax.set(xlabel='Frequency (Hz)',
... ylabel='Weighting (log10)',
... title='B-Weighting of CQT frequencies')
"""
f_sq = np.asanyarray(frequencies) ** 2.0
const = np.array([12194.217, 20.598997, 158.48932]) ** 2.0
weights = 0.17 + 20.0 * (
np.log10(const[0])
+ 1.5 * np.log10(f_sq)
- np.log10(f_sq + const[0])
- np.log10(f_sq + const[1])
- 0.5 * np.log10(f_sq + const[2])
)
return weights if min_db is None else np.maximum(min_db, weights)
@deprecate_positional_args
def C_weighting(frequencies, *, min_db=-80.0): # pylint: disable=invalid-name
"""Compute the C-weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
min_db : float [scalar] or None
Clip weights below this threshold.
If `None`, no clipping is performed.
Returns
-------
C_weighting : scalar or np.ndarray [shape=(n,)]
``C_weighting[i]`` is the C-weighting of ``frequencies[i]``
See Also
--------
perceptual_weighting
frequency_weighting
multi_frequency_weighting
A_weighting
B_weighting
D_weighting
Examples
--------
Get the C-weighting for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weights = librosa.C_weighting(freqs)
>>> fig, ax = plt.subplots()
>>> ax.plot(freqs, weights)
>>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)',
... title='C-Weighting of CQT frequencies')
"""
f_sq = np.asanyarray(frequencies) ** 2.0
const = np.array([12194.217, 20.598997]) ** 2.0
weights = 0.062 + 20.0 * (
np.log10(const[0])
+ np.log10(f_sq)
- np.log10(f_sq + const[0])
- np.log10(f_sq + const[1])
)
return weights if min_db is None else np.maximum(min_db, weights)
@deprecate_positional_args
def D_weighting(frequencies, *, min_db=-80.0): # pylint: disable=invalid-name
"""Compute the D-weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
min_db : float [scalar] or None
Clip weights below this threshold.
If `None`, no clipping is performed.
Returns
-------
D_weighting : scalar or np.ndarray [shape=(n,)]
``D_weighting[i]`` is the D-weighting of ``frequencies[i]``
See Also
--------
perceptual_weighting
frequency_weighting
multi_frequency_weighting
A_weighting
B_weighting
C_weighting
Examples
--------
Get the D-weighting for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weights = librosa.D_weighting(freqs)
>>> fig, ax = plt.subplots()
>>> ax.plot(freqs, weights)
>>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)',
... title='D-Weighting of CQT frequencies')
"""
f_sq = np.asanyarray(frequencies) ** 2.0
const = np.array([8.3046305e-3, 1018.7, 1039.6, 3136.5, 3424, 282.7, 1160]) ** 2.0
weights = 20.0 * (
0.5 * np.log10(f_sq)
- np.log10(const[0])
+ 0.5
* (
+np.log10((const[1] - f_sq) ** 2 + const[2] * f_sq)
- np.log10((const[3] - f_sq) ** 2 + const[4] * f_sq)
- np.log10(const[5] + f_sq)
- np.log10(const[6] + f_sq)
)
)
return weights if min_db is None else np.maximum(min_db, weights)
@deprecate_positional_args
def Z_weighting(frequencies, *, min_db=None): # pylint: disable=invalid-name
weights = np.zeros(len(frequencies))
return weights if min_db is None else np.maximum(min_db, weights)
WEIGHTING_FUNCTIONS = {
"A": A_weighting,
"B": B_weighting,
"C": C_weighting,
"D": D_weighting,
"Z": Z_weighting,
None: Z_weighting,
}
@deprecate_positional_args
def frequency_weighting(frequencies, *, kind="A", **kwargs):
"""Compute the weighting of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
kind : str in
The weighting kind. e.g. `'A'`, `'B'`, `'C'`, `'D'`, `'Z'`
**kwargs
Additional keyword arguments to A_weighting, B_weighting, etc.
Returns
-------
weighting : scalar or np.ndarray [shape=(n,)]
``weighting[i]`` is the weighting of ``frequencies[i]``
See Also
--------
perceptual_weighting
multi_frequency_weighting
A_weighting
B_weighting
C_weighting
D_weighting
Examples
--------
Get the A-weighting for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weights = librosa.frequency_weighting(freqs, kind='A')
>>> fig, ax = plt.subplots()
>>> ax.plot(freqs, weights)
>>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)',
... title='A-Weighting of CQT frequencies')
"""
if isinstance(kind, str):
kind = kind.upper()
return WEIGHTING_FUNCTIONS[kind](frequencies, **kwargs)
@deprecate_positional_args
def multi_frequency_weighting(frequencies, *, kinds="ZAC", **kwargs):
"""Compute multiple weightings of a set of frequencies.
Parameters
----------
frequencies : scalar or np.ndarray [shape=(n,)]
One or more frequencies (in Hz)
kinds : list or tuple or str
An iterable of weighting kinds. e.g. `('Z', 'B')`, `'ZAD'`, `'C'`
**kwargs : keywords to pass to the weighting function.
Returns
-------
weighting : scalar or np.ndarray [shape=(len(kinds), n)]
``weighting[i, j]`` is the weighting of ``frequencies[j]``
using the curve determined by ``kinds[i]``.
See Also
--------
perceptual_weighting
frequency_weighting
A_weighting
B_weighting
C_weighting
D_weighting
Examples
--------
Get the A, B, C, D, and Z weightings for CQT frequencies
>>> import matplotlib.pyplot as plt
>>> freqs = librosa.cqt_frequencies(n_bins=108, fmin=librosa.note_to_hz('C1'))
>>> weightings = 'ABCDZ'
>>> weights = librosa.multi_frequency_weighting(freqs, kinds=weightings)
>>> fig, ax = plt.subplots()
>>> for label, w in zip(weightings, weights):
... ax.plot(freqs, w, label=label)
>>> ax.set(xlabel='Frequency (Hz)', ylabel='Weighting (log10)',
... title='Weightings of CQT frequencies')
>>> ax.legend()
"""
return np.stack(
[frequency_weighting(frequencies, kind=k, **kwargs) for k in kinds], axis=0
)
@deprecate_positional_args
def times_like(X, *, sr=22050, hop_length=512, n_fft=None, axis=-1):
"""Return an array of time values to match the time axis from a feature matrix.
Parameters
----------
X : np.ndarray or scalar
- If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram.
- If scalar, X represents the number of frames.
sr : number > 0 [scalar]
audio sampling rate
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``n_fft // 2``
to counteract windowing effects when using a non-centered STFT.
axis : int [scalar]
The axis representing the time axis of X.
By default, the last axis (-1) is taken.
Returns
-------
times : np.ndarray [shape=(n,)]
ndarray of times (in seconds) corresponding to each frame of X.
See Also
--------
samples_like :
Return an array of sample indices to match the time axis from a feature matrix.
Examples
--------
Provide a feature matrix input:
>>> y, sr = librosa.load(librosa.ex('trumpet'))
>>> D = librosa.stft(y)
>>> times = librosa.times_like(D)
>>> times
array([0. , 0.023, ..., 5.294, 5.317])
Provide a scalar input:
>>> n_frames = 2647
>>> times = librosa.times_like(n_frames)
>>> times
array([ 0.00000000e+00, 2.32199546e-02, 4.64399093e-02, ...,
6.13935601e+01, 6.14167800e+01, 6.14400000e+01])
"""
samples = samples_like(X, hop_length=hop_length, n_fft=n_fft, axis=axis)
return samples_to_time(samples, sr=sr)
@deprecate_positional_args
def samples_like(X, *, hop_length=512, n_fft=None, axis=-1):
"""Return an array of sample indices to match the time axis from a feature matrix.
Parameters
----------
X : np.ndarray or scalar
- If ndarray, X is a feature matrix, e.g. STFT, chromagram, or mel spectrogram.
- If scalar, X represents the number of frames.
hop_length : int > 0 [scalar]
number of samples between successive frames
n_fft : None or int > 0 [scalar]
Optional: length of the FFT window.
If given, time conversion will include an offset of ``n_fft // 2``
to counteract windowing effects when using a non-centered STFT.
axis : int [scalar]
The axis representing the time axis of ``X``.
By default, the last axis (-1) is taken.
Returns
-------
samples : np.ndarray [shape=(n,)]
ndarray of sample indices corresponding to each frame of ``X``.
See Also
--------
times_like :
Return an array of time values to match the time axis from a feature matrix.
Examples
--------
Provide a feature matrix input:
>>> y, sr = librosa.load(librosa.ex('trumpet'))
>>> X = librosa.stft(y)
>>> samples = librosa.samples_like(X)
>>> samples
array([ 0, 512, ..., 116736, 117248])
Provide a scalar input:
>>> n_frames = 2647
>>> samples = librosa.samples_like(n_frames)
>>> samples
array([ 0, 512, 1024, ..., 1353728, 1354240, 1354752])
"""
if np.isscalar(X):
frames = np.arange(X)
else:
frames = np.arange(X.shape[axis])
return frames_to_samples(frames, hop_length=hop_length, n_fft=n_fft)
@deprecate_positional_args
def midi_to_svara_h(midi, *, Sa, abbr=True, octave=True, unicode=True):
"""Convert MIDI numbers to Hindustani svara
Parameters
----------
midi : numeric or np.ndarray
The MIDI number or numbers to convert
Sa : number > 0
MIDI number of the reference Sa.
abbr : bool
If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...)
If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information.
If `False`, use low-order ASCII (' and ,) for octave decorations.
This only takes effect if `octave=True`.
Returns
-------
svara : str or list of str
The svara corresponding to the given MIDI number(s)
See Also
--------
hz_to_svara_h
note_to_svara_h
midi_to_svara_c
midi_to_note
Examples
--------
The first three svara with Sa at midi number 60:
>>> librosa.midi_svara_h([60, 61, 62], Sa=60)
['S', 'r', 'R']
With Sa=67, midi 60-62 are in the octave below:
>>> librosa.midi_to_svara_h([60, 61, 62], Sa=67)
['ṃ', 'Ṃ', 'P̣']
Or without unicode decoration:
>>> librosa.midi_to_svara_h([60, 61, 62], Sa=67, unicode=False)
['m,', 'M,', 'P,']
Or going up an octave, with Sa=60, and using unabbreviated notes
>>> librosa.midi_to_svara_h([72, 73, 74], Sa=60, abbr=False)
['Ṡa', 'ṙe', 'Ṙe']
"""
SVARA_MAP = [
"Sa",
"re",
"Re",
"ga",
"Ga",
"ma",
"Ma",
"Pa",
"dha",
"Dha",
"ni",
"Ni",
]
SVARA_MAP_SHORT = list(s[0] for s in SVARA_MAP)
if not np.isscalar(midi):
return [
midi_to_svara_h(m, Sa=Sa, abbr=abbr, octave=octave, unicode=unicode)
for m in midi
]
svara_num = int(np.round(midi - Sa))
if abbr:
svara = SVARA_MAP_SHORT[svara_num % 12]
else:
svara = SVARA_MAP[svara_num % 12]
if octave:
if 24 > svara_num >= 12:
if unicode:
svara = svara[0] + "\u0307" + svara[1:]
else:
svara += "'"
elif -12 <= svara_num < 0:
if unicode:
svara = svara[0] + "\u0323" + svara[1:]
else:
svara += ","
return svara
@deprecate_positional_args
def hz_to_svara_h(frequencies, *, Sa, abbr=True, octave=True, unicode=True):
"""Convert frequencies (in Hz) to Hindustani svara
Note that this conversion assumes 12-tone equal temperament.
Parameters
----------
frequencies : positive number or np.ndarray
The frequencies (in Hz) to convert
Sa : positive number
Frequency (in Hz) of the reference Sa.
abbr : bool
If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...)
If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information.
If `False`, use low-order ASCII (' and ,) for octave decorations.
This only takes effect if `octave=True`.
Returns
-------
svara : str or list of str
The svara corresponding to the given frequency/frequencies
See Also
--------
midi_to_svara_h
note_to_svara_h
hz_to_svara_c
hz_to_note
Examples
--------
Convert Sa in three octaves:
>>> librosa.hz_to_svara_h([261/2, 261, 261*2], Sa=261)
['Ṣ', 'S', 'Ṡ']
Convert one octave worth of frequencies with full names:
>>> freqs = librosa.cqt_frequencies(n_bins=12, fmin=261)
>>> librosa.hz_to_svara_h(freqs, Sa=freqs[0], abbr=False)
['Sa', 're', 'Re', 'ga', 'Ga', 'ma', 'Ma', 'Pa', 'dha', 'Dha', 'ni', 'Ni']
"""
midis = hz_to_midi(frequencies)
return midi_to_svara_h(
midis, Sa=hz_to_midi(Sa), abbr=abbr, octave=octave, unicode=unicode
)
@deprecate_positional_args
def note_to_svara_h(notes, *, Sa, abbr=True, octave=True, unicode=True):
"""Convert western notes to Hindustani svara
Note that this conversion assumes 12-tone equal temperament.
Parameters
----------
notes : str or list of str
Notes to convert (e.g., `'C#'` or `['C4', 'Db4', 'D4']`
Sa : str
Note corresponding to Sa (e.g., `'C'` or `'C5'`).
If no octave information is provided, it will default to octave 0
(``C0`` ~= 16 Hz)
abbr : bool
If `True` (default) return abbreviated names ('S', 'r', 'R', 'g', 'G', ...)
If `False`, return long-form names ('Sa', 're', 'Re', 'ga', 'Ga', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information.
If `False`, use low-order ASCII (' and ,) for octave decorations.
This only takes effect if `octave=True`.
Returns
-------
svara : str or list of str
The svara corresponding to the given notes
See Also
--------
midi_to_svara_h
hz_to_svara_h
note_to_svara_c
note_to_midi
note_to_hz
Examples
--------
>>> librosa.note_to_svara_h(['C4', 'G4', 'C5', 'G5'], Sa='C5')
['Ṣ', 'P̣', 'S', 'P']
"""
midis = note_to_midi(notes, round_midi=False)
return midi_to_svara_h(
midis, Sa=note_to_midi(Sa), abbr=abbr, octave=octave, unicode=unicode
)
@deprecate_positional_args
def midi_to_svara_c(midi, *, Sa, mela, abbr=True, octave=True, unicode=True):
"""Convert MIDI numbers to Carnatic svara within a given melakarta raga
Parameters
----------
midi : numeric
The MIDI numbers to convert
Sa : number > 0
MIDI number of the reference Sa.
Default: 60 (261.6 Hz, `C4`)
mela : int or str
The name or index of the melakarta raga
abbr : bool
If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...)
If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information and subscript
numbers.
If `False`, use low-order ASCII (' and ,) for octave decorations.
Returns
-------
svara : str or list of str
The svara corresponding to the given MIDI number(s)
See Also
--------
hz_to_svara_c
note_to_svara_c
mela_to_degrees
mela_to_svara
list_mela
"""
if not np.isscalar(midi):
return [
midi_to_svara_c(
m, Sa=Sa, mela=mela, abbr=abbr, octave=octave, unicode=unicode
)
for m in midi
]
svara_num = int(np.round(midi - Sa))
svara_map = notation.mela_to_svara(mela, abbr=abbr, unicode=unicode)
svara = svara_map[svara_num % 12]
if octave:
if 24 > svara_num >= 12:
if unicode:
svara = svara[0] + "\u0307" + svara[1:]
else:
svara += "'"
elif -12 <= svara_num < 0:
if unicode:
svara = svara[0] + "\u0323" + svara[1:]
else:
svara += ","
return svara
@deprecate_positional_args
def hz_to_svara_c(frequencies, *, Sa, mela, abbr=True, octave=True, unicode=True):
"""Convert frequencies (in Hz) to Carnatic svara
Note that this conversion assumes 12-tone equal temperament.
Parameters
----------
frequencies : positive number or np.ndarray
The frequencies (in Hz) to convert
Sa : positive number
Frequency (in Hz) of the reference Sa.
mela : int [1, 72] or string
The melakarta raga to use.
abbr : bool
If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...)
If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information.
If `False`, use low-order ASCII (' and ,) for octave decorations.
This only takes effect if `octave=True`.
Returns
-------
svara : str or list of str
The svara corresponding to the given frequency/frequencies
See Also
--------
note_to_svara_c
midi_to_svara_c
hz_to_svara_h
hz_to_note
list_mela
Examples
--------
Convert Sa in three octaves:
>>> librosa.hz_to_svara_c([261/2, 261, 261*2], Sa=261, mela='kanakangi')
['Ṣ', 'S', 'Ṡ']
Convert one octave worth of frequencies using melakarta #36:
>>> freqs = librosa.cqt_frequencies(n_bins=12, fmin=261)
>>> librosa.hz_to_svara_c(freqs, Sa=freqs[0], mela=36)
['S', 'R₁', 'R₂', 'R₃', 'G₃', 'M₁', 'M₂', 'P', 'D₁', 'D₂', 'D₃', 'N₃']
"""
midis = hz_to_midi(frequencies)
return midi_to_svara_c(
midis, Sa=hz_to_midi(Sa), mela=mela, abbr=abbr, octave=octave, unicode=unicode
)
@deprecate_positional_args
def note_to_svara_c(notes, *, Sa, mela, abbr=True, octave=True, unicode=True):
"""Convert western notes to Carnatic svara
Note that this conversion assumes 12-tone equal temperament.
Parameters
----------
notes : str or list of str
Notes to convert (e.g., `'C#'` or `['C4', 'Db4', 'D4']`
Sa : str
Note corresponding to Sa (e.g., `'C'` or `'C5'`).
If no octave information is provided, it will default to octave 0
(``C0`` ~= 16 Hz)
mela : str or int [1, 72]
Melakarta raga name or index
abbr : bool
If `True` (default) return abbreviated names ('S', 'R1', 'R2', 'G1', 'G2', ...)
If `False`, return long-form names ('Sa', 'Ri1', 'Ri2', 'Ga1', 'Ga2', ...)
octave : bool
If `True`, decorate svara in neighboring octaves with over- or under-dots.
If `False`, ignore octave height information.
unicode : bool
If `True`, use unicode symbols to decorate octave information.
If `False`, use low-order ASCII (' and ,) for octave decorations.
This only takes effect if `octave=True`.
Returns
-------
svara : str or list of str
The svara corresponding to the given notes
See Also
--------
midi_to_svara_c
hz_to_svara_c
note_to_svara_h
note_to_midi
note_to_hz
list_mela
Examples
--------
>>> librosa.note_to_svara_h(['C4', 'G4', 'C5', 'D5', 'G5'], Sa='C5', mela=1)
['Ṣ', 'P̣', 'S', 'G₁', 'P']
"""
midis = note_to_midi(notes, round_midi=False)
return midi_to_svara_c(
midis, Sa=note_to_midi(Sa), mela=mela, abbr=abbr, octave=octave, unicode=unicode
)
|