Python多媒体处理

1.利用 sounddevice, SoundFile, pydub 库,读取一段音乐的音频文件
(music.wav)并播放,依次去掉该音乐的第 2,4 ……等偶数秒
内的音频,然后保存为一个新的音频文件。
2. 读取一个文本文件(alphatwice.txt),统计该文件内英文字母(区分大小
写)的出现次数,选择出现次数最高的 10 个英文字母,利用 matplotlib 库
绘制“字母-次数”直方图,最后将直方图保存为一个图像文件。

多媒体处理-音频处理
首先需要安装所需库:
pip install sounddevice
pip install soundfile
pip install pydub

然后可以使用以下代码实现:
import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment
import os

# 读取音频文件
filename = 'music.wav'
data, sr = sf.read(filename)

# 播放音频
sd.play(data, sr)

# 去掉偶数秒的音频
new_data = []
for i in range(len(data)):
    if i % sr % 2 != 0:
        new_data.append(data[i])

# 将新音频保存为文件
new_filename = 'new_music.wav'
sf.write(new_filename, new_data, sr)

# 停止播放音频
sd.stop()
sd.wait()

# 播放新音频
new_data, sr = sf.read(new_filename)
sd.play(new_data, sr)
sd.wait()

多媒体处理-文本处理
首先需要安装所需库:
pip install matplotlib

然后可以使用以下代码实现:
import matplotlib.pyplot as plt
import string

# 读取文本文件
filename = 'alphatwice.txt'
with open(filename, 'r') as f:
    text = f.read()

# 统计英文字母出现次数
letter_count = {}
for letter in string.ascii_letters:
    letter_count[letter] = text.count(letter)

# 获取出现次数最高的 10 个字母
top_letters = sorted(letter_count.items(), key=lambda x: x[1], reverse=True)[:10]
x = [i[0] for i in top_letters]
y = [i[1] for i in top_letters]

# 绘制直方图
plt.bar(x, y)
plt.xlabel('Letter')
plt.ylabel('Count')
plt.title('Letter Count')
plt.savefig('letter_count.png')
plt.show()

第一个

import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment

#读取音频文件
filename = 'music.wav'
data, sample_rate = sf.read(filename)

# 播放音频文件
sd.play(data, sample_rate)
sd.wait()

# 去掉偶数秒内的音频并保存
new_data = []
for i in range(len(data)):
 if i % (2 * sample_rate) >= sample_rate:
 new_data.append(data[i])
new_data = np.array(new_data)

#保存新的音频文件
new_filename = 'new_music.wav'
sf.write(new_filename, new_data, sample_rate)

# 播放新的音频文件
new_audio = AudioSegment.from_file(new_filename, format='wav')
new_audio.export('new_music.mp3', format='mp3')

第二个

import matplotlib.pyplot as plt

#读取文本文件
filename = 'alphatwice.txt'
with open(filename, 'r') as f:
 text = f.read()

# 统计字母出现次数
count = {}
for char in text:
 if char.isalpha():
 char = char.lower()
 count[char] = count.get(char,0) +1

#选择出现次数最高的10个字母
top_chars = sorted(count.items(), key=lambda x:x[1], reverse=True)[:10]
x = [char[0] for char in top_chars]
y = [char[1] for char in top_chars]

# 绘制直方图
plt.bar(x, y)
plt.title('Top10 Letters')
plt.xlabel('Letters')
plt.ylabel('Counts')

#保存为图像文件
plt.savefig('letter_counts.png')

以下是实现音频文件处理和文本统计并绘制直方图并保存图像的Python代码。请注意,此代码假定在同一目录中存在输入的音频文件和文本文件,并且将在相同目录中创建输出文件和图像文件。

import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment
import string
import matplotlib.pyplot as plt

# 处理音频文件
data, fs = sf.read('music.wav')
sd.play(data, fs)
while sd.get_running(): pass
for i in range(1, int(len(data)/(2*fs))+1):
    start = int(2*i*fs)
    end = min(int((2*i+1)*fs), len(data))
    data[start:end] = 0
sf.write('music_without_even_seconds.wav', data, fs)

# 处理文本文件
alphatwice = open('alphatwice.txt', 'r')
text = alphatwice.read().lower()
alphatwice.close()
count = {}
for char in text:
    if char in string.ascii_lowercase:
        if char in count:
            count[char] += 1
        else:
            count[char] = 1
top_chars = sorted(count.items(), key=lambda x: x[1], reverse=True)[:10]
labels, values = zip(*top_chars)
plt.bar(labels, values)
plt.savefig('top_10_chars.png')
这是一个Python多媒体处理的问题,需要使用 sounddevice, SoundFile, pydub 库来读取音频文件,并使用 matplotlib 库来绘制直方图。
1. 读取音频文件并播放
首先需要安装 sounddevice, SoundFile, pydub 库。可以使用以下命令进行安装:

pip install sounddevice
pip install soundfile
pip install pydub

然后可以使用以下代码读取音频文件并播放:
python
import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment
# 读取音频文件
audio_file = AudioSegment.from_wav("music.wav")
# 播放音频文件
sd.play(audio_file.raw_data, audio_file.frame_rate)
sd.wait()

2. 去掉偶数秒内的音频并保存为新的音频文件
可以使用 pydub 库的 split_to_mono() 方法将音频文件转换为单声道,然后使用 pydub 库的 split() 方法将音频文件分割成每秒一段。然后可以使用以下代码去掉偶数秒内的音频并保存为新的音频文件:
python
# 将音频文件转换为单声道
audio_file = audio_file.split_to_mono()[0]
# 将音频文件分割成每秒一段
segments = audio_file.split(1000)
# 去掉偶数秒内的音频
for i in range(len(segments)):
if i % 2 == 1:
segments[i] = AudioSegment.silent(duration=1000)
# 合并音频文件
new_audio_file = segments[0]
for i in range(1, len(segments)):
new_audio_file += segments[i]
# 保存新的音频文件
new_audio_file.export("new_music.wav", format="wav")

3. 统计文本文件内英文字母出现次数并绘制直方图
可以使用 Python 内置的 Counter 类来统计文本文件内英文字母出现次数,然后使用 matplotlib 库来绘制直方图。可以使用以下代码实现:
python
import matplotlib.pyplot as plt
from collections import Counter
# 读取文本文件
with open("alphatwice.txt", "r") as f:
text = f.read()
# 统计英文字母出现次数
counter = Counter(text.lower())
top_10 = counter.most_common(10)
# 绘制直方图
plt.bar([x[0] for x in top_10], [x[1] for x in top_10])
plt.xlabel("Letter")
plt.ylabel("Count")
plt.title("Top 10 Letters in alphatwice.txt")
plt.savefig("letter_count.png")

去掉偶数秒的音频并保存为新的音频文件


import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment
# 读取音频文件
data, samplerate = sf.read('music.wav')
# 播放原始音频
sd.play(data, samplerate)
sd.wait()
# 将音频转为AudioSegment对象
audio = AudioSegment.from_wav('music.wav')
# 去掉偶数秒的音频
audio_cut = audio[::2]
# 播放去掉偶数秒的音频
audio_cut.export('music_cut.wav', format='wav')
data_cut, samplerate_cut = sf.read('music_cut.wav')
sd.play(data_cut, samplerate_cut)
sd.wait()

统计文本文件内英文字母的出现次数并绘制直方图

import matplotlib.pyplot as plt
# 读取文本文件
with open('alphatwice.txt', 'r') as f:
    text = f.read()
# 统计字母出现次数
letter_count = {}
for letter in text:
    if letter.isalpha():
        letter = letter.lower()
        if letter in letter_count:
            letter_count[letter] += 1
        else:
            letter_count[letter] = 1
# 选择出现次数最高的10个字母
top_letters = sorted(letter_count.items(), key=lambda x: x[1], reverse=True)[:10]
# 绘制直方图
plt.bar(range(len(top_letters)), [x[1] for x in top_letters])
plt.xticks(range(len(top_letters)), [x[0].upper() for x in top_letters])
plt.xlabel('Letter')
plt.ylabel('Count')
plt.title('Top 10 letters in alphatwice.txt')
plt.savefig('letter_count.png')
plt.show()

以下答案由GPT-3.5大模型与博主波罗歌共同编写:

  1. 音频文件处理代码:
import sounddevice as sd
import soundfile as sf
from pydub import AudioSegment

# read input audio file
audio_file = 'music.wav'
data, samplerate = sf.read(audio_file)

# play original audio
sd.play(data, samplerate)
sd.wait()

# remove even seconds from audio file
audio = AudioSegment.from_wav(audio_file)
for i in range(2, len(audio)):
    if (i % 2 == 0):
        audio = audio[:i * 1000] + audio[i * 1000 + 1000:]
audio.export('new_music.wav', format='wav')

# read new audio file
data, samplerate = sf.read('new_music.wav')

# play new audio
sd.play(data, samplerate)
sd.wait()
  1. 文本文件处理代码:
import string
from collections import Counter
import matplotlib.pyplot as plt

# read input text file
with open("alphatwice.txt") as f:
    text = f.read()

# remove punctuation and convert to lowercase
text = text.translate(text.maketrans('', '', string.punctuation)).lower()

# count occurences of each letter
letter_counts = Counter(text)

# select top 10 most frequent letters
top_letters = sorted(letter_counts.items(), key=lambda x: x[1], reverse=True)[:10]

# extract letters and counts
letters = [item[0] for item in top_letters]
counts = [item[1] for item in top_letters]

# plot histogram of letter counts
plt.bar(letters, counts)
plt.xlabel('Letter')
plt.ylabel('Count')
plt.savefig('letter_counts.png')

如果我的回答解决了您的问题,请采纳!