0

我想创建一个类似文件的对象,稍后将通过其文件名打开该对象。有可能这样做吗?我正在寻找这样的东西:

import io

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

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

我查看了这个线程,但之后无法通过其名称访问该文件。

为了完整起见,我想具体做的是生成正弦波形并在Android环境中播放。这是改编自此答案的代码。

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"))

我也对允许我在 Android 上播放机器生成的声音的其他解决方案持开放态度。感谢您的帮助!

4

1 回答 1

0

俗话说“过早的优化是万恶之源”,对吧?

根据@fins 的评论,我创建了临时文件来使用库tempfile存储音频。当文件关闭时,它会自动销毁文件。

这是我在问题中发布的工作版本:

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"))
于 2018-08-15T10:19:54.103 回答