Python音频处理,录制播放

一、内容

  • Simpleaudio:支持numpy数组播放

  • sounddevice 和 soundfile:支持播放和录制包含音频信号的 NumPy 数组

  • pydub:必须预先安装至少一个来自(simpleaudio、pyaudio、ffplay 和 avplay)的音频播放包。可以查看音频信息(时长,分贝)

  • pyaudio 和 wave:录制和连续音频流

二、pyaudio录音和播放

  1. 播放

import pyaudio
import wave

filename = 'path-to_file.wav'

# Set chunk size of 1024 samples per data frame
chunk = 1024 

# Open the soaudio/sound file
af = wave.open(filename, 'rb')

# Create an interface to PortAudio
pa = pyaudio.PyAudio()

# Open a .Stream object to write the WAV file
# 'output = True' indicates that the
# sound will be played rather than
# recorded and opposite can be used for recording
stream = pa.open(format = pa.get_format_from_width(af.getsampwidth()),
                channels = af.getnchannels(),
                rate = af.getframerate(),
                output = True)

# Read data in chunks
rd_data = af.readframes(chunk)

# Play the sound by writing the audio
# data to the Stream using while loop
while rd_data != '':
    stream.write(rd_data)
    rd_data = af.readframes(chunk)

# Close and terminate the stream
stream.stop_stream()
stream.close()
pa.terminate()

2. 录制

import pyaudio
import wave

# Record in chunks of 1024 samples
chunk = 1024 

# 16 bits per sample
sample_format = pyaudio.paInt16 
chanels = 2

# Record at 44400 samples per second
smpl_rt = 44400 
seconds = 4
filename = "path_of_file.wav"

# Create an interface to PortAudio
pa = pyaudio.PyAudio() 

stream = pa.open(format=sample_format, channels=chanels,
                 rate=smpl_rt, input=True,
                 frames_per_buffer=chunk)

print('Recording...')

# Initialize array that be used for storing frames
frames = [] 

# Store data in chunks for 8 seconds
for i in range(0, int(smpl_rt / chunk * seconds)):
    data = stream.read(chunk)
    frames.append(data)

# Stop and close the stream
stream.stop_stream()
stream.close()

# Terminate - PortAudio interface
pa.terminate()

print('Done !!! ')

# Save the recorded data in a .wav format
sf = wave.open(filename, 'wb')
sf.setnchannels(chanels)
sf.setsampwidth(pa.get_sample_size(sample_format))
sf.setframerate(smpl_rt)
sf.writeframes(b''.join(frames))
sf.close()

三、pydub调整音量

1、调整音量大小

读取文件

from pydub import AudioSegment
from pydub.playback import play

audio = AudioSegment.from_mp3('./1.mp3')
#tape = AudioSegment.from_wav('path_to_myfile.wav')
#tape = AudioSegment.from_file('path_to_myfile.wav', format='wav')

#放大6db音量
audio_big = audio + 6

#减弱3db音量
audio_small = audio - 3
play(audio)

2 、音频切片

获取录音的某个时间段,以毫秒为单位。

start = 10000
end   = 20000
audio_temp = audio[start:end]

References

https://www.moonapi.com/news/2810.html

你可能感兴趣的:(Python开发,音视频)