首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何将numpy数组转换为mp3文件

如何将numpy数组转换为mp3文件
EN

Stack Overflow用户
提问于 2021-02-14 08:59:25
回答 1查看 757关注 0票数 0

我正在使用声卡库来记录我的麦克风输入,它记录在一个NumPy数组中,我想抓取音频并将其保存为mp3文件。

代码:

代码语言:javascript
复制
import soundcard as sc
import numpy 
import threading


speakers = sc.all_speakers() # Gets a list of the systems speakers
default_speaker = sc.default_speaker() # Gets the default speaker
mics = sc.all_microphones() # Gets a list of all the microphones


default_mic = sc.get_microphone('Headset Microphone (Arctis 7 Chat)') # Gets the default microphone


# Records the default microphone
def record_mic():
  print('Recording...')
  with default_mic.recorder(samplerate=48000) as mic, default_speaker.player(samplerate=48000) as sp:
      for _ in range(1000000000000):
          data = mic.record(numframes=None) # 'None' creates zero latency
          sp.play(data) 
          
          # Save the mp3 file here 


recordThread = threading.Thread(target=record_mic)
recordThread.start()
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2021-02-14 09:20:26

使用Scipy (到wav文件)

您可以很容易地转换为wav,然后分别转换wav到mp3。更多细节here

代码语言:javascript
复制
from scipy.io.wavfile import write

samplerate = 44100; fs = 100
t = np.linspace(0., 1., samplerate)

amplitude = np.iinfo(np.int16).max
data = amplitude * np.sin(2. * np.pi * fs * t)

write("example.wav", samplerate, data.astype(np.int16))

使用pydub (到mp3)

从这个优秀的thread中尝试这个函数-

代码语言:javascript
复制
import pydub 
import numpy as np

def write(f, sr, x, normalized=False):
    """numpy array to MP3"""
    channels = 2 if (x.ndim == 2 and x.shape[1] == 2) else 1
    if normalized:  # normalized array - each item should be a float in [-1, 1)
        y = np.int16(x * 2 ** 15)
    else:
        y = np.int16(x)
    song = pydub.AudioSegment(y.tobytes(), frame_rate=sr, sample_width=2, channels=channels)
    song.export(f, format="mp3", bitrate="320k")

#[[-225  707]
# [-234  782]
# [-205  755]
# ..., 
# [ 303   89]
# [ 337   69]
# [ 274   89]]

write('out2.mp3', sr, x)

注意:因为MP3s总是16位的,所以输出MP3当然是16位的。但是,您可以按照@Arty的建议为24位输入设置sample_width=3

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/66191480

复制
相关文章

相似问题

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