Commit 05bf1d72 authored by blackheaven's avatar blackheaven
Browse files

Add 10s trimmed function

parent 405240a1
Loading
Loading
Loading
Loading

.gitignore

0 → 100644
+2 −0
Original line number Diff line number Diff line
output.mp3
tmp/
+15 −7
Original line number Diff line number Diff line
{
    "_meta": {
        "hash": {
            "sha256": "295fa60b4ad3b19ec29744ec2dfafba79ad5ee9a0b9ff095ac626e3d3981f117"
            "sha256": "aed7e6b3b5a441a7ecc30493011b8219a30ef6888efb4adb5d11456eb3497236"
        },
        "pipfile-spec": 6,
        "requires": {
@@ -34,11 +34,11 @@
        },
        "flask": {
            "hashes": [
                "sha256:8ba2a854608fdd603b67dccd4514a46450132227fb9df40127a8d0c1de8769ec",
                "sha256:a6059db4297106e5a64b3215fa16ae641822c1cb97ecb498573549b2478602cb"
                "sha256:77fd4e1249d8c9923de34907236b747ced06e5467ecac1a7bb7115ae0e9670b0",
                "sha256:8c2f9abd47a9e8df7f0c3f091ce9497d011dc3b31effcf4c85a6e2b50f4114ef"
            ],
            "index": "pypi",
            "version": "==2.3.1"
            "version": "==2.3.2"
        },
        "itsdangerous": {
            "hashes": [
@@ -112,13 +112,21 @@
            "markers": "python_version >= '3.7'",
            "version": "==2.1.2"
        },
        "pydub": {
            "hashes": [
                "sha256:65617e33033874b59d87db603aa1ed450633288aefead953b30bded59cb599a6",
                "sha256:980a33ce9949cab2a569606b65674d748ecbca4f0796887fd6f46173a7b0d30f"
            ],
            "index": "pypi",
            "version": "==0.25.1"
        },
        "werkzeug": {
            "hashes": [
                "sha256:2f3278e9ef61511cdf82cc28fc5da0f5b501dd8f01ecf5ef6a5d810048f68702",
                "sha256:b7b8bc1609f35ae8e45d48a9b58d7a4eb1e41eec148d37e977e5df6ebf3398b2"
                "sha256:1d5a58e0377d1fe39d061a5de4469e414e78ccb1e1e59c0f5ad6fa1c36c52b76",
                "sha256:48e5e61472fee0ddee27ebad085614ebedb7af41e88f687aaf881afb723a162f"
            ],
            "markers": "python_version >= '3.8'",
            "version": "==2.3.2"
            "version": "==2.3.4"
        }
    },
    "develop": {}
+17 −5
Original line number Diff line number Diff line
@@ -2,9 +2,11 @@
#from flask import Flask, request, send_file
import os
import random
from flask import Flask, send_from_directory
from flask import Flask, send_file
from werkzeug.serving import run_simple

# audio trim
from pydub import AudioSegment
from random import randint

# Your API definition
app = Flask(__name__)
@@ -19,12 +21,22 @@ def healthcheck():

@app.route('/bgm/<emotion>', methods=['GET'])
def bgm(emotion):
    absolute_path = os.path.dirname(__file__)
    # absolute_path = os.path.dirname(__file__)
    # relative_path = "src/lib"
    full_path = os.path.join(absolute_path, emotion)
    # full_path = os.path.join(absolute_path, emotion)
    files = [f for f in os.listdir(emotion) if f.endswith('.mp3')]
    selected_file = random.choice(files)
    return send_from_directory(emotion, selected_file, as_attachment=False)
    full_path = os.path.join(emotion, selected_file)
    sound = AudioSegment.from_mp3(full_path)
    sound_time = len(sound)
    def get_trimmed(sound, sound_time):
        playtime = 10000
        initial = randint(0, (sound_time - playtime))
        end = initial + playtime
        sound[initial:end].export('output.mp3', format='mp3')
        # return sound[initial:end]
    get_trimmed(sound, sound_time)
    return send_file('output.mp3', as_attachment=False)

if __name__ == '__main__':
    app.run(host='0.0.0.0', port='50005', debug=True)

get_trimmed2.ipynb

0 → 100644
+50 −0
Original line number Diff line number Diff line
%% Cell type:markdown id:d4a4f8cf-db75-432b-92e0-3300ad46a844 tags:

### get_trimmed 수정본, trim파일에 있는 get_trimmed오류 해결

%% Cell type:code id:6a32c646-e980-4128-94a9-2e4e4717aa02 tags:

``` python
from pydub import AudioSegment
from random import randint

# mp3이름을 넣고, 시작시간과 종료시간을 설정함
# 원하는 시간에서 시작하여 원하는 시간까지 잘라내어 가져온다.
# 시작 시간을 랜덤하게 설정하고 싶다면. 위 밀리초로 변환한 시간 범위 안에서 랜덤하게 선택하면 될 듯

# initial은 랜덤으로 설정한다.
# sound = AudioSegment.from_mp3(mp3_filename)
sound = AudioSegment.from_mp3("SaloonRag.mp3")
sound_time = len(sound) # 밀리초 단위인듯?

print("sound_time ", sound_time)


def get_trimmed(sound, sound_time):
#     오디오 재생시간 밀리초로 설정
    playtime = 10000
#     만약 파일 이름이 존재하지 않는다면, 디렉토리에 없다는 오류 문구 출력
#     if (not mp3_filename):
#         # raise an error to immediately halt program execution
#         raise Exception("No MP3 found in local directory.")

    # reads mp3 as a PyDub object
#   mp3 파일을 불러와서 AudioSegment 객체 생성
#     sound = AudioSegment.from_mp3(mp3_filename)

#   자르기 시작할 시간을 밀리초로 변환하여 t0으로 지정
#     t0 = get_video_time_in_ms(initial) - playtime

#   오디오 재생 시작시간 설정. 0에서부터 재생시간을 제외한 오디오 시간에서 랜덤하게 선택
    initial = randint(0, (sound_time - playtime))
#     print("Beginning trimming process for file ", mp3_filename, ".\n")
    print("Starting from ", initial, "...")

#   initial 보다 10000ms 뒤를 end로 설정
    end = initial + playtime

#   시작시간부터, 10초 이후까지 (end = initial+10000은 initial보다 10초 더 많은 시간을 의미)
    return sound[initial:end]

get_trimmed(sound, sound_time)
```