简体   繁体   English

python-按文件名打开类似文件的对象

[英]python - Open filelike object by filename

I want to create a filelike object that will later be opened by its filename. 我想创建一个类似文件的对象,稍后将通过其文件名打开它。 Is it possible to do that? 有可能这样做吗? I'm looking for something like this: 我正在寻找这样的东西:

import io

fileLikeObject = io.BytesIO()
fileLikeObject.write((b"randomContent")
fileLikeObject.name = "someFilename.txt"

sameFileAsbefore = open("someFilename.txt", "rb")
sameFileAsbefore.read()

I've looked at this thread , but the file is not accessible by its name afterwards. 我已经看过了这个线程 ,但是以后无法通过文件名访问该文件。

For completeness, what I want to specifically do is to generate a sinusoidal waveform and play in an Android environment. 为了完整起见,我要专门做的是生成一个正弦波形并在Android环境中播放。 Here is a code adapted from this answer . 这是根据此答案改编而成的代码。

from kivy.core.audio import SoundLoader
from kivy.base import runTouchApp
from kivy.uix.button import Button
import time


# Wave parameters
fs = 44100 # sampling frequency
duration = 2 # seconds

# Generating waveforms
timePoints = np.linspace(0, duration, duration*fs)
sineWave = np.sin(2 * np.pi * 440 * timePoints) # 440 Hz
outdata = np.transpose(np.tile(volume*outputWave, (2,1)))

class MyLabel(Button):
    def on_release(self):
        start_time = time.time()
        self.play_sound()
        print("--- %s seconds ---" % (time.time() - start_time))

    def play_sound(self):

        bytes_out = io.BytesIO()
        wavfile.write(bytes_out, fs, outdata)
        bytes_out.seek(0)

        sound = SoundLoader.load(bytes_out) # only loads by filename :/
        sound.seek(0)

        if sound:
            print("Sound found at %s" % sound.source)
            print("Sound is %.3f seconds" % sound.length)
            sound.play()

runTouchApp(MyLabel(text="Press me for a sound"))

I'm also open to other solutions that allow me to play machine-generated sounds on Android. 我也欢迎其他解决方案,使我能够在Android上播放机器生成的声音。 Thanks for helping! 感谢您的帮助!

As the saying goes, "premature optimization is the source of all evil", right? 俗话说,“过早的优化是万恶之源”,对吗?

Based on @fins' comment, I've created temporary files to store the audio using the library tempfile . 基于@fins的注释,我创建了临时文件来使用tempfile库存储音频。 It automatically destroys the file when it is closed. 关闭文件时,它将自动销毁文件。

Here's the working version for what I've posted in the question: 这是我在问题中发布的内容的工作版本:

from kivy.core.audio import SoundLoader
from kivy.base import runTouchApp
from kivy.uix.button import Button
from scipy.io import wavfile
import time
import tempfile
import numpy as np

# Wave parameters
fs = 44100 # sampling frequency
duration = 2 # seconds

# Generating waveforms
timePoints = np.linspace(0, duration, duration*fs)
sineWave = np.sin(2 * np.pi * 440 * timePoints) # 440 Hz
outdata = np.transpose(np.tile(sineWave, (2,1)))

class MyLabel(Button):
    def on_release(self):
        start_time = time.time()
        self.play_sound()
        print("--- %s seconds ---" % (time.time() - start_time))

    def play_sound(self):

        f = tempfile.NamedTemporaryFile(suffix = '.wav', delete=True)
        wavfile.write(f, fs, outdata)
        f.seek(0)

        sound = SoundLoader.load(f.name)

        if sound:
            print("Sound found at %s" % sound.source)
            print("Sound is %.3f seconds" % sound.length)
            sound.play()

        f.close()

runTouchApp(MyLabel(text="Press me for a sound"))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM