【python】可指定时间播放音频噪声

【诉求】

A是一段音频,它有个长度是9秒,A_2就是播放A段音频的前2s。传入播放的时间time,效果是播放对应时常的音频。抽象出来:time = 输出音频的种类对应的长度

str audioList = [A,B,C]
Int audioLength = [9,9,10]
All_audio_Length = 28

time
如果播放时间time是7s,播放A_7
如果播放时间time是14s,播放A + B_5
如果播放时间time是20s,播放A + B + C_2
如果播放时间time是30s,播放A + B + C + A_2

【实现】

def test(time):
    result = ""
    audioList = ["A","B"]
    audioLengtList = [9,9]

    curTime = 0
    i = 0
    while time > curTime:
        for i in range(len(audioList)):
            curTime += audioLengtList[i]
            if result != "":
                result += "+"
            if time > curTime:
                result += audioList[i]
                continue
            elif time == curTime:
                result += audioList[i]
                break
            elif time < curTime:
                needless = curTime - time
                need = audioLengtList[i] - needless
                result += audioList[i] + "_" + str(need)
                break
        i = i % len(audioList)

    print(result)
    return result

if __name__ == '__main__':
    test(50)

【调用pygame实现音频播放】

pygame.mixer.Sound(“”)
Hello from the pygame community. https://www.pygame.org/contribute.html

import pygame
import argparse

def audioPlay(time):
    # 初始化 pygame
    global sound
    pygame.init()

    # 创建音频对象
    pygame.mixer.init()

    AudioList = ["dog.wav","aircon.wav"]
    AudioLengthList = []
    for i in AudioList:
        a = int(pygame.mixer.Sound(i).get_length())
        AudioLengthList.append(a)

    curTime = 0
    i = 0
    result = ""
    while time > curTime:
        for i in range(len(AudioList)):
            curTime += AudioLengthList[i]
            if result != "":
                result += "+"
            if time > curTime:
                result += AudioList[i]
                sound = pygame.mixer.Sound(AudioList[i])
                sound.play()
                pygame.time.wait(int(sound.get_length())*1000)
                continue
            elif time == curTime:
                result += AudioList[i]
                sound = pygame.mixer.Sound(AudioList[i])
                sound.play()
                pygame.time.wait(int(sound.get_length())*1000)
                break
            elif time < curTime:
                needless = curTime - time
                need = AudioLengthList[i] - needless
                result += AudioList[i] + "_" + str(need)

                sound = pygame.mixer.Sound(AudioList[i])
                sound.play()
                pygame.time.wait(need*1000)

                break
        i = i % len(AudioList)
    print(result)
    return result


if __name__ == '__main__':
    # parser = argparse.ArgumentParser()
    # parser.add_argument('-t', '--time', default='', type=int, required=False, help="Execution time")
    # args = parser.parse_args()
    # t = args.time

    audioPlay(30)

你可能感兴趣的:(python,音视频,pygame)