如何让Ruby Gosu通过变量正确加载文件路径播放音频?
问题分析与解决方案
核心问题
使用Gosu播放音乐时,直接写入绝对路径能正常播放,但通过变量拼接生成的路径却报错无法打开文件,且File.exist?返回false,但路径在资源管理器中能正常访问。
可能原因及对应解决步骤
1. 路径字符串截断或包含隐藏字符
错误信息中显示路径被截断:
Couldn't open c:/Users/ultra/OneDrive/Documents/schoolstuff/uni/sem 1/programming stuff/programming work/portfolio/Distinction T
这说明传递给Gosu的路径可能不完整,或者字符串中存在不可见字符。
解决方法:
在代码中添加调试代码,查看路径的真实内容:
puts music_path.inspect # 用inspect可显示字符串中的隐藏字符、转义符
如果发现有多余空格或不可见字符,清理track_path:
track_path = track.location.to_s.strip # 去除首尾空格
2. 路径构建方式不规范
手动拼接路径容易因分隔符、相对路径逻辑出错,建议用Ruby自带的File.join规范路径构建,替代直接使用File.expand_path:
# 替换原路径构建代码 base_dir = File.dirname(__FILE__) music_path = File.expand_path(File.join(base_dir, track_path))
File.join会自动根据系统环境选择正确的路径分隔符(Windows下为反斜杠),避免跨平台或分隔符错误。
3. OneDrive路径的特殊重定向
OneDrive的路径可能存在虚拟重定向,导致Ruby的File模块无法识别实际本地文件位置。
解决方法:
尝试获取文件的真实本地路径,或确保文件已同步到本地:
# 先检查文件是否存在,若不存在尝试解析OneDrive真实路径(Windows环境) if File.exist?(music_path) @song = Gosu::Song.new(music_path) else # 通过cmd命令获取真实路径 real_path = `cmd /c echo #{music_path}`.strip @song = Gosu::Song.new(real_path) end
同时检查OneDrive文件状态,确保文件不是"仅在线"状态(右键文件查看同步状态)。
4. 权限问题
Ruby进程可能没有访问OneDrive目录的权限,尝试以管理员身份运行Ruby脚本,或检查文件的权限设置。
修正后的示例代码
def playTrack(track_name, album) track = album.tracks.find { |t| t.name == track_name } return unless track # 提前判断track是否存在 track_path = track.location.to_s.strip base_dir = File.dirname(__FILE__) music_path = File.expand_path(File.join(base_dir, track_path)) puts "尝试加载路径:#{music_path.inspect}" # 先检查文件是否存在 if File.exist?(music_path) @song = Gosu::Song.new(music_path) @song.play(false) else puts "文件不存在:#{music_path}" # 尝试OneDrive真实路径 begin real_path = `cmd /c echo #{music_path}`.strip @song = Gosu::Song.new(real_path) @song.play(false) rescue => e puts "加载失败:#{e.message}" end end end
内容的提问来源于stack exchange,提问作者Yari
相关产品推荐
相关产品推荐

