![](/img/trans.png)
[英]How to use getAssets().open(filename) with FileWriter?
[英]python - Open filelike object by filename
我想創建一個類似文件的對象,稍后將通過其文件名打開它。 有可能這樣做嗎? 我正在尋找這樣的東西:
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上播放機器生成的聲音。 感謝您的幫助!
俗話說,“過早的優化是萬惡之源”,對嗎?
基於@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"))
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.