LoginSignup
2
2

More than 5 years have passed since last update.

Titanium で binary データをファイルに書き込む方法

Posted at

Titanium は内部的に Blob を使っている箇所もあり、画像データや HTTPClient で取得したデータなどは、Binary でファイルに書き出すことができます。

ただ、プログラム中で作った Binary っぽいデータなど(音声データや動画データなど)は、
普通に filewrite するだけではうまくいかない場合があります。

そんな時は、Ti.Buffer を使ってみるといいと思います。

function pack(fmt, data) {
    var result = '';
    //... implement 'V' only
    switch (fmt) {
    case 'V':
        result += String.fromCharCode(data & 0xFF);
        result += String.fromCharCode(data >> 8 & 0xFF);
        result += String.fromCharCode(data >> 16 & 0xFF);
        result += String.fromCharCode(data >> 24 & 0xFF);
    }
    return result;
}

// Binary っぽいファイルを Binary でちゃんと出力する
var blob, buff, file;

blob = [
    'fmt ',
    pack('V', 16),
    pack('V', 44100)
].join('');

buff = Ti.createBuffer({length: blob.length});
for (var i = 0; i < blob.length; i++) {
    buff[i] = blob.charCodeAt(i)
}

file = Ti.Filesystem.getFile(Ti.Filesystem.tempDirectory, "binary");
file.write(buff.toBlob());

Binary っぽいデータを一度 Ti.Buffer に書き込み、toBlob を使ってバイナリ化して書き込みます。

普通に書きだしたとき

\xC2 というデータが書き出されてしまっている。リトルエンディアンで処理しているバイナリデータをUTF-8で書きだすからなんか変になっているのではないかと。
普通に書きだしたとき

Blob で書きだしたとき

\xC2 は書き出されていない。
Bufferで書きだしたとき

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2