Polly将mp3下载为int?尝试使用Lambda将其安装到S3

时间:2019-05-31 20:33:26

标签: python amazon-s3 aws-lambda amazon-polly

我是Python的初学者。试图找出Polly的问题所在,因为它似乎没有输出有效的mp3。

我正在松散地关注这些教程:1 2

但是由于字符限制,我没有串联任何文件,所以我认为我不需要使用Audiosegment或ffmpeg吗?

这是我的代码:

import hashlib
import json
import tempfile
import praw, boto3
import os
import random
import time

polly = boto3.client('polly')
s3 = boto3.client('s3')
s3r = boto3.resource('s3')

DEFAULT_VOICE = os.getenv("DEFAULT_VOICE", "Celine")
SAMPLE_RATE = os.getenv("SAMPLE_RATE", "8000")
BUCKET_NAME = os.getenv("BUCKET_NAME", "pollybotreddit")
FILE_FORMAT = os.getenv("FILE_FORMAT", "mp3")

def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    with open('test.mp3' , 'wb') as f:
        sound = f.write(resp['AudioStream'].read())
    return sound

def lambda_handler(event, content):
    slashr = event.get('subreddit')
    voice = event.get('voice', 'Joanna')
    if not slashr:
        raise ValueError("Bad Request: Not a subreddit")

    reddit = praw.Reddit('bot1')
    sub = reddit.subreddit(slashr)
    titles = []
    for submission in sub.hot(limit=5):
        if not submission.stickied:
            titles.append(submission.title)
    article = random.choice(titles)

    sound_data = build_sound(article, voice=voice)
    final = sound_data + '.mp3'


    s3.put_object(Bucket=BUCKET_NAME, ACL='public-read', Body=final, Key=article)

    item = {
        'subreddit': slashr,
        's3': "{}/{}/{}".format(s3.meta.endpoint_url, BUCKET_NAME, article)
        }
    return item

lambda_handler({'subreddit':"politics"}, None)

错误给了我这个

  File "pollybot.py", line 91, in <module>
    lambda_handler({'subreddit':"politics"}, None)
  File "pollybot.py", line 79, in lambda_handler
    final = sound_data + '.mp3'
TypeError: unsupported operand type(s) for +: 'int' and 'str'

如果我拿出

final = sound_data + '.mp3'

Polly的输出仍然是int,而不是File对象,因此它给了我

botocore.exceptions.ParamValidationError: Parameter validation failed:
Invalid type for parameter Body, value: 3493, type: <class 'int'>, valid types: <class 'bytes'>, <class 'bytearray'>, file-like object

有帮助吗?预先感谢。

1 个答案:

答案 0 :(得分:0)

感谢@Daniel Roseman,以下代码块对我有用:

def build_sound(content, voice = 'Justin', SampleRate = SAMPLE_RATE):
    for text in content:
        resp = polly.synthesize_speech(
            OutputFormat = "mp3",
            Text = text,
            TextType = "text",
            VoiceId = voice
        )
    filetospeech = resp['AudioStream'].read()
    return filetospeech