python怎么合成音乐_Python合成音乐

这篇博客展示了如何使用Python读取music.json文件中的音符频率映射,通过定义的合成器函数生成音频信号,并将一系列音符组合成两段音乐music1和music2,最终将它们保存为wav文件。
摘要由CSDN通过智能技术生成

我们可以利用Python合成音频,同样也能合成一些音乐,这里我们有个文件music.json里定义了A~F以及对应的频率,简单合成了两段音乐music1、music2,供读者参考学习。

import json

import numpy as np

from scipy.io.wavfile import write

import matplotlib.pyplot as plt

#----------------------定义合成器---------------------def synthesizer(freq, duration, amp=1.0, sampling_freq=44100):

t = np.linspace(0, duration, duration * sampling_freq)

audio = amp * np.sin(2 * np.pi * freq * t)

return audio.astype(np.int16)

if __name__=='__main__':

tone_map_file = 'music.json'

with open(tone_map_file, 'r') as f:

tone_freq_map = json.loads(f.read())

input_tone='G'

duration = 2     # seconds    amplitude = 10000

sampling_freq = 44100    # Hz

# Tone-duration sequence

tone_seq = [('D', 1), ('G',1), ('C',1), ('A',1),

('B',1),('F',1),('A',1),('Gsharp',4),

('B',1),('F',1),('G',1),('Csharp',1),

('Dsharp',1),('Csharp',1),('Gsharp',1),('Asharp', 2),

('D', 1), ('G',1), ('C',1), ('A',1),

('B',3),('F',1),('G',1),('Csharp',1),

('Dsharp',3),('E',1),('Fsharp',1),('Asharp', 5)]

#-------------------------------------------------------------

tone_seq1 = [('E', 2), ('C',1), ('D',1), ('E',1),

('D',1),('C',1),('B',1),('A',1),

('C',0),('E',0),('Asharp',0),('G',0),

('G',0),('Asharp',1),('G',1),('F', 2),

('G', 1), ('Asharp',2), ('E',2),('E', 2),

('C',1), ('D',1), ('E',1),('D',1),('C',1),('B',1),

('A',1), ('A',1), ('B',3),('F',1),('G',1),('Asharp',1),

('Dsharp',3),('E',1),('Fsharp',1),('Asharp', 5)]

#---------------------------------------------------------------

# Construct the audio signal based on the chord sequence

output = np.array([])

for item in tone_seq:

input_tone = item[0]

duration = item[1]

synthesized_tone = synthesizer(tone_freq_map[input_tone], duration, amplitude, sampling_freq)

output = np.append(output, synthesized_tone, axis=0)

#===============================================================

# Write to the output file

write('music1.wav', sampling_freq, output)

for item in tone_seq1:

input_tone = item[0]

duration = item[1]

synthesized_tone = synthesizer(tone_freq_map[input_tone], duration, amplitude, sampling_freq)

output = np.append(output, synthesized_tone, axis=0)

write('music2.wav', sampling_freq, output)

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值