【发布时间】:2021-08-09 06:04:00
【问题描述】:
我正在尝试在 C++ 中从头开始创建一个 MIDI 文件。 我正在使用这个网站作为资源:https://intuitive-theory.com/midi-from-scratch/。
由于 MIDI 要求它以十六进制编码,我编写了一个程序来创建一个 MIDI 文件并将 HEX 代码粘贴到其中,如下所示:
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <iomanip>
#include <stdio.h>
using namespace std;
int main(){
ofstream myfile;
myfile.open ("output.mid",ios::binary);
char buffer[44] = {static_cast<char>(0x4D,0x54,0x68,0x64,0x00,0x00,0x00,0x06,0x00,0x01,0x00,0x01,0x00,0x80,0x4D,0x54,0x72,0x6B,0x00,0x00,0x00,0x16,0x80,0x00,0x90,0x3C,0x60,0x81,0x00,0x3E,0x60,0x81,0x00,0x40,0x60,0x81,0x00,0xB0,0x7B,0x00,0x00,0xFF,0x2F,0x00)};
myfile.write(buffer,44);
myfile.close();
}
但是,由于“文件已损坏”,它甚至无法在任何 MIDI 播放器上打开。我不明白为什么会这样。
谢谢
【问题讨论】:
-
static_cast<char>(0x4D,0x54,...)不会将该列表中的所有项目都转换为chars it is casting the last one and discarding the rest。 -
你为什么在这里使用
static_cast? -
@tadman 有些数字太大,很可能无法放入
signed char。 -
@user4581301 那么是时候确定
unsigned char或uint8_t了。 -
建议:创建一个
unsigned char的数组,并在对write的调用中将其转换为char*。例如:unsigned char buffer[44] = {0x4D,0x54,0x68,0x64,0x00,...};,然后是myfile.write(reinterpret_cast<char*>(buffer),sizeof(buffer));。注意:一般来说,要非常非常小心reinterpret_cast。它告诉编译器关掉它的大脑并相信你。如果你错了,程序会 be goofy 并且你不会收到任何警告。