You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用irrKlang播放用户输入路径的音频文件?

解决irrKlang结合getline读取带空格路径的播放问题

核心问题分析

你遇到的问题并非需要把string转成ISoundSource*,而是没注意到irrklang::ISoundEngine::play2D的重载版本,以及std::string到C风格字符串的转换方式:

  • play2D有直接接受文件路径(const char*)的重载,不需要先转成ISoundSource*
  • std::string可以通过c_str()方法获取对应的const char*指针,满足irrKlang的参数要求

修正后的代码

#include <iostream>
#include <string>
#include <irrKlang.h>

using namespace std;
using namespace irrklang;

int main()
{
    ISoundEngine* engine = createIrrKlangDevice();
    if (!engine) { // 增加设备创建失败的判断
        cerr << "Failed to create sound engine!" << endl;
        return 1;
    }

    cout << "Enter path to sound: ";
    string filename;
    getline(cin, filename); // 补充分号修正语法错误

    // 方式1:直接传递路径的C风格字符串给play2D
    engine->play2D(filename.c_str()); 

    // 方式2:先加载为ISoundSource*再播放(适合重复播放的场景)
    // ISoundSource* soundSource = engine->addSoundSourceFromFile(filename.c_str());
    // if (soundSource) {
    //     engine->play2D(soundSource);
    // } else {
    //     cerr << "Failed to load sound source!" << endl;
    // }

    system("pause"); // 防止程序直接退出,等待用户操作
    engine->drop(); // 释放引擎资源
    return 0;
}

关键说明

  • getline(cin, filename)读取完整路径后,通过filename.c_str()将std::string转换为irrKlang能识别的C风格字符串(const char*)
  • 若需要重复播放同一音频,推荐先调用addSoundSourceFromFile加载为ISoundSource*,避免重复读取文件,提升性能
  • 代码补充了设备创建失败判断、资源释放逻辑,保证程序健壮性

内容的提问来源于stack exchange,提问作者Tetrapak

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:52:36