コード例 #1
0
String FileUtils::OpenProjectFileDialog()
{
    nfdchar_t *outPath = NULL;

    String upath;

#ifdef ATOMIC_PLATFORM_LINUX
    upath = GetSubsystem<FileSystem>()->GetUserDocumentsDir();
#endif

    nfdresult_t result = NFD_OpenDialog( "atomic",
                                upath.Length() ? GetNativePath(upath).CString() : "",
                                &outPath);

    String fullpath;

    if (outPath && result == NFD_OKAY)
    {
        fullpath = outPath;
    }

    GetSubsystem<Graphics>()->RaiseWindow();

    if (outPath)
        free(outPath);

    return fullpath;

}
コード例 #2
0
ファイル: FileDialog.cpp プロジェクト: bubba169/lime
	const char* FileDialog::OpenFile (const char* filter, const char* defaultPath) {
		
		nfdchar_t *savePath = 0;
		nfdresult_t result = NFD_OpenDialog (filter, defaultPath, &savePath);
		
		switch (result) {
			
			case NFD_OKAY:
				
				return savePath;
				break;
			
			case NFD_CANCEL:
				
				break;
			
			default:
				
				printf ("Error: %s\n", NFD_GetError ());
				break;
			
		}
		
		return savePath;
		
	}
コード例 #3
0
void UIPathSelector::OpenDialog(){
  nfdchar_t *outPath = nullptr;
  nfdresult_t result = NFD_OpenDialog( NULL, (path=="") ? NULL : path.c_str() , &outPath );
  if(result == NFD_OKAY){
    path = outPath;
    on_selected.Happen(path);
    child_entry->SetText(path);
    free(outPath);
  }
}
コード例 #4
0
ファイル: app.cpp プロジェクト: fabioarnold/TwoTriangles
void App::openShaderDialog() {
	char *out_filepath = nullptr;
	nfdresult_t result = NFD_OpenDialog("frag,glsl,fsh,txt", nullptr, &out_filepath);
	SDL_RaiseWindow(sdl_window); // workaround: focus window again after dialog closes
	
	if (result == NFD_OKAY) {
		struct stat attr;
		if (!stat(out_filepath, &attr)) { // file exists
			shader_file_mtime = (int)attr.st_mtime;
			loadShader(out_filepath);
		}
		free(out_filepath);
	}
}
コード例 #5
0
ファイル: app.cpp プロジェクト: bryongloden/TwoTriangles
void App::openShaderDialog() {
	char *out_file_path = nullptr;
	nfdresult_t result = NFD_OpenDialog("frag,glsl,fsh,txt", nullptr, &out_file_path);
	SDL_RaiseWindow(sdl_window); // workaround: focus window again after dialog closes
	
	if (result == NFD_OKAY) {
		if (file_path) free(file_path);
		file_path = out_file_path;

		struct stat attr;
		if (!stat(file_path, &attr)) { // file exists
			file_mod_time = attr.st_mtime;
			loadShader(file_path, /*initial*/true);
		}
	}
}
コード例 #6
0
ファイル: FileDialog.cpp プロジェクト: jackpoz/G3D-backup
bool FileDialog::getFilename(String& filename, const String& extension, bool isSave) {
    char * finalFilename = (char *)malloc(sizeof(char) * BUFSIZ);
    const String& fname = FileSystem::NFDStandardizeFilename(filename);
    nfdresult_t result;
    if (isSave) {
        result = NFD_SaveDialog(extension.c_str(), fname.c_str(), &finalFilename);
    } else {
        result = NFD_OpenDialog(extension.c_str(), fname.c_str(), &finalFilename);
    }
    if (result == NFD_OKAY) {
        filename = String(finalFilename);
        if (isSave && !endsWith(filename, extension)) {
            filename += "." + extension;
        }
    }
    return (result == NFD_OKAY);
}
コード例 #7
0
String FileUtils::FindFile (const String& filterlist, const String& defaultPath)
{
    String fullpath;
    nfdchar_t *outPath = NULL;

    nfdresult_t result = NFD_OpenDialog( filterlist.CString(),
        defaultPath.Length() ? GetNativePath(defaultPath).CString() : "",
        &outPath);

    if (outPath && result == NFD_OKAY)
    {
        fullpath = outPath;
    }

    GetSubsystem<Graphics>()->RaiseWindow();

    if (outPath)
        free(outPath);

    return fullpath;
}
コード例 #8
0
String FileUtils::GetMobileProvisionPath()
{
    nfdchar_t *outPath = NULL;

    nfdresult_t result = NFD_OpenDialog( "mobileprovision",
                                "",
                                &outPath);

    String fullpath;

    if (outPath && result == NFD_OKAY)
    {
         fullpath = outPath;
    }

    GetSubsystem<Graphics>()->RaiseWindow();

    if (outPath)
        free(outPath);

    return fullpath;

}
コード例 #9
0
String FileUtils::OpenProjectFileDialog()
{
    nfdchar_t *outPath = NULL;

    nfdresult_t result = NFD_OpenDialog( "atomic",
                                NULL,
                                &outPath);

    String fullpath;

    if (outPath && result == NFD_OKAY)
    {
        fullpath = outPath;
    }

    GetSubsystem<Graphics>()->RaiseWindow();

    if (outPath)
        free(outPath);

    return fullpath;

}
コード例 #10
0
ファイル: app.cpp プロジェクト: fabioarnold/TwoTriangles
void App::openImageDialog(TextureSlot *texture_slot, bool load_cube_cross) {
	char *out_filepath = nullptr;
	nfdresult_t result = NFD_OpenDialog("tga,png,bmp,jpg,hdr", nullptr, &out_filepath);
	SDL_RaiseWindow(sdl_window); // workaround: focus window again after dialog closes

	if (result == NFD_OKAY) {
		if (load_cube_cross) {
			int out_size;
			GLuint loaded_texture_cube = loadTextureCubeCross(out_filepath,
				/*build_mipmaps*/true, &out_size);
			if (loaded_texture_cube) {
				texture_slot->clear();

				texture_slot->target = GL_TEXTURE_CUBE_MAP;
				texture_slot->texture = loaded_texture_cube;
				texture_slot->image_width = out_size;
				texture_slot->image_height = out_size;
				texture_slot->image_filepath = out_filepath;
			}
		} else {
			int out_width, out_height;
			GLuint loaded_texture = loadTexture2D(out_filepath,
				/*build_mipmaps*/true, &out_width, &out_height);
			if (loaded_texture) { // loading successful
				texture_slot->clear();

				texture_slot->target = GL_TEXTURE_2D;
				setWrapTexture2D(GL_REPEAT, GL_REPEAT);
				texture_slot->texture = loaded_texture;
				texture_slot->image_width = out_width;
				texture_slot->image_height = out_height;
				texture_slot->image_filepath = out_filepath;
			}
		}
	}
}
コード例 #11
0
ファイル: Game.cpp プロジェクト: exnotime/DV1508AssetTool
void Game::Update(float dt){
	m_BrushBlock = false;
	///////////////////////////////////////////////////////////////////////////////
	UpdateModelViewWindow(dt);	
	///////////////////////////////////////////////////////////////////////////////
	m_BrushArea.Update();
	m_LoadModelButton.Update();

	//check if we should close
	m_CloseProgramButton.Update();
	if (m_CloseProgramButton.IsClicked()) glfwSetWindowShouldClose(gfx::g_GFXEngine.GetWindow(), GL_TRUE);
	// Load model button
	if (m_LoadModelButton.IsClicked())
	{
		nfdchar_t *outPath = NULL;
		nfdresult_t result = NFD_OpenDialog("obj,dae", "", &outPath);
		if (result == NFD_OKAY)
		{
			gfx::g_ModelBank.Clear();
			//gfx::g_MaterialBank.ClearMaterials();
			m_Model = gfx::g_ModelBank.LoadModel(outPath);
			gfx::g_ModelBank.BuildBuffers();
			m_SelectedVertices.clear();

			m_uvTranslation.ResetList();
		}
	}
	m_ColorPickerButton.Update();
	if (m_ColorPickerButton.IsClicked()){
		m_colorPicker.TogglePicker();
	}
	static float h = 0;
	static float oldh = 0;
	ImGui::SliderFloat("Hardness", &h, 0, 1);
	if (h != oldh){
		m_BrushGenerator.GenerateTexture(64, h, m_TestSprite.GetTexture());
	}
	oldh = h;
	TempSelectVertices( m_Model, m_SelectedVertices );	// TODO: Remove when real vertice selection is implemented.
	m_VerticeTranslation.SetSelectedVertices( m_SelectedVertices );
	m_VerticeTranslation.Update( dt );

	// UV
	m_uvTranslation.Update(dt);
	m_uvButton.Update();
	if (m_uvButton.IsClicked())
	{
		m_uvTranslation.Toggle();
	}

	SetWireFrameState(m_VerticeSelection.Update(dt));

	m_colorPicker.Update();

	// Relations manager.
	m_RelationsButton.Update();
	if (m_RelationsButton.IsClicked())
	{
		if (m_RelationsToggled)
		{
			m_RelationsToggled = false;
		}

		else
		{
			m_RelationsToggled = true;
		}
	}

	if (m_uvTranslation.IsActive())
	{
		m_BrushBlock = true;
	}
	else
	{
		m_BrushBlock = m_colorPicker.IsActive();
	}

	m_minimize.Update();

	for (unsigned int i = 0; i < m_FakeButtons.size(); i++)
	{
		m_FakeButtons[i].Update();
	}
}
コード例 #12
0
ファイル: main.cpp プロジェクト: begumcig/Audio-Signals
int main()
{
	cout << "Software by Elif Begum Cig" << endl << "For any questions email [email protected]." << endl
		<< "Any recorded file is automaticly saved." << endl << "Recordings are made at 16 bits but you can convert it to 8 bits." << endl;

	sf::RenderWindow window(sf::VideoMode(1340, 390), "Recorder", sf::Style::Close); 
	window.setKeyRepeatEnabled(false);
	window.setFramerateLimit(60);

	sf::SoundBufferRecorder recorder;
	sf::SoundBuffer record;
	sf::SoundBuffer waver;
	sf::Sound sound;
	sf::RectangleShape rectangle;//for the waveform.
	sf::Font font;
	sf::Clock playtime;
	sf::Clock playtime1;


	if (!font.loadFromFile("OpenSans-Regular.ttf"))
	{
		cout << "Could not load the font file." << endl;
	}

	int recCount44 = 0; // the variables that hold the number of records corresponding to their sampling frequencies.
	int recCount22 = 0;
	int recCount11 = 0;
	int recCount50 = 0;
	bool last1 = false; //when playing the sounds we have to know which sample rated audio we are using.
	bool last2 = false;
	bool last3 = false;
	bool last4 = false;
	vector <int> ycor;
	bool bpause = false;
	bool bplay = false;
	sf::Time duration = sf::seconds(18000);
	sf::Time interval = sf::seconds(0);

	// some UI elements.
	sf::Text record1;
	record1.setFont(font);
	record1.setString("Hold 1 to record at 44100 Hz.");
	record1.setColor(sf::Color::White);
	record1.setPosition(20, 20);
	record1.setCharacterSize(17);

	sf::Text record2;
	record2.setFont(font);
	record2.setString("Hold 2 to record at 22100 Hz.");
	record2.setColor(sf::Color::White);
	record2.setPosition(20, 40);
	record2.setCharacterSize(17);

	sf::Text record3;
	record3.setFont(font);
	record3.setString("Hold 3 to record at 11050 Hz.");
	record3.setColor(sf::Color::White);
	record3.setPosition(20,60);
	record3.setCharacterSize(17);

	sf::Text record4;
	record4.setFont(font);
	record4.setString("Hold 4 to record at 5012 Hz.");
	record4.setColor(sf::Color::White);
	record4.setPosition(20, 80);
	record4.setCharacterSize(17);

	sf::Text rec;
	rec.setFont(font);
	rec.setPosition(1200, 30);
	rec.setCharacterSize(22);

	sf::Text opent;
	opent.setFont(font);
	opent.setString("O - Open File");
	opent.setColor(sf::Color::White);
	opent.setPosition(1150, 330);
	opent.setCharacterSize(17);

	sf::Text playt;
	playt.setFont(font);
	playt.setString("P - Play last recording");
	playt.setColor(sf::Color::White);
	playt.setPosition(1150, 350);
	playt.setCharacterSize(17);

	sf::Text pause;
	pause.setFont(font);
	pause.setString("Space - Play/Pause");
	pause.setColor(sf::Color::White);
	pause.setPosition(600, 20);
	pause.setCharacterSize(17);


	sf::Text playpauset;
	playpauset.setFont(font);
	playpauset.setColor(sf::Color::Red);
	playpauset.setPosition(630, 39);
	playpauset.setCharacterSize(20);

	sf::Text bit8t;
	bit8t.setFont(font);
	bit8t.setColor(sf::Color::White);
	bit8t.setString("Press 8 to convert to 8 bit.");
	bit8t.setPosition(20, 345);
	bit8t.setCharacterSize(17);




	//the main loop.
	while (window.isOpen())
	{
		sf::Event event;
		while (window.pollEvent(event))
		{
			if (event.type == sf::Event::Closed)
				window.close();

			// the part for recording at different sampling frequencies. The key 1 -> 44100hz, 2-> 22050hz, 3-> 11025hz and 4->5012hz.
			if (event.type == sf::Event::KeyPressed &&(event.key.code == sf::Keyboard::Num1 || event.key.code == sf::Keyboard::Num2 || event.key.code == sf::Keyboard::Num3 || event.key.code == sf::Keyboard::Num4)) // if the 1,2,3 or 4 key is pressed start recording (at 44100, 22050, 11025, 5012Hz)
			{
				rec.setString("Recording...");
				rec.setColor(sf::Color::White);

				if(event.key.code == sf::Keyboard::Num1)
				{
					if (sf::SoundBufferRecorder::isAvailable()) //if recording is available start recording.
					{
						recorder.start(44100);
						recCount44++;	//this will be used for naming the files whlist savin.
					}
				}

				else if(event.key.code == sf::Keyboard::Num2)
				{
					if (sf::SoundBufferRecorder::isAvailable())
					{
						recorder.start(22050);
						recCount22++;
					}
				}

				else if(event.key.code == sf::Keyboard::Num3)
				{
					if (sf::SoundBufferRecorder::isAvailable()) 
					{
						recorder.start(11025);
						recCount11++;
					}
				}

				else if(event.key.code == sf::Keyboard::Num4)
				{
					if (sf::SoundBufferRecorder::isAvailable()) 
					{
						recorder.start(5012);
						recCount50++;
					}
				}
			}

			//what to do when the pressed keys are let go.
			if (event.type == sf::Event::KeyReleased)
			{
				rec.setString("");
				if(event.key.code == sf::Keyboard::Num1)
				{
					recorder.stop();
					// Get the buffer containing the captured audio data
					const sf::SoundBuffer& buffer = recorder.getBuffer();
					// Save it to a file
					string count = itoa(recCount44); //return the string equivalent of the number of recordings which has been done at 44100hz.
					buffer.saveToFile("recording 44100 - " + count + ".wav");
					last1 = true; //the last recording was made at 44100hz.
					last2 = false;
					last3 = false;
					last4 = false;
				}

				else if(event.key.code == sf::Keyboard::Num2)
				{
					recorder.stop();
					// Get the buffer containing the captured audio data
					const sf::SoundBuffer& buffer = recorder.getBuffer();
					// Save it to a file
					string count = itoa(recCount22); //return the string equivalent of the number of recordings which has been done at 22050hz.
					buffer.saveToFile("recording 22050 - " + count + ".wav");
					last1 = false;
					last2 = true; //the last recording was made at 22050hz.
					last3 = false;
					last4 = false;
				}
				else if(event.key.code == sf::Keyboard::Num3)
				{
					recorder.stop();
					// Get the buffer containing the captured audio data
					const sf::SoundBuffer& buffer = recorder.getBuffer();
					// Save it to a file
					string count = itoa(recCount11); //return the string equivalent of the number of recordings which has been done at 11025hz.
					buffer.saveToFile("recording 11025 - " + count + ".wav");
					last1 = false;
					last2 = false;
					last3 = true; //the last recording was made at 11025 hz.
					last4 = false;
				}
				else if(event.key.code == sf::Keyboard::Num4)
				{
					recorder.stop();
					// Get the buffer containing the captured audio data
					const sf::SoundBuffer& buffer = recorder.getBuffer();
					// Save it to a file
					string count = itoa(recCount50); //return the string equivalent of the number of recordings which has been done at 5012hz.
					buffer.saveToFile("recording 5012 - " + count + ".wav");
					last1 = false;
					last2 = false;
					last3 = false;
					last4 = true; //the last recording mas done in 5012hz.
				}

			}

			//time condition to make play pause option available
			//in sfml a clock starts as soon as it is contructed, therefore some precautions should be taken for play/pause to work properly.
			//playtime is the first clock and it only holds true iff the user never presses play/pause.
			//since playtime also counts when the audio pauses, playtime1 resets when the audio plays again and its value is incremented in interval.
			//since playtime1 resets when the audio starts, we should make sure that it can start. bpause is true when audio pauses and false when it starts.
			if(playtime.getElapsedTime() >= duration && playtime1.getElapsedTime() + interval >= duration && bpause==false)
			{
				bplay = false;
				playpauset.setString("");
				sf::Time sec0 = sf::seconds(0);
				interval = sec0;
			}

			//the part about playing pausing the audio
			if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space && bplay == true)
			{
				if(bpause)
				{
					sound.play();
					playtime1.restart(); //playtime1 begins to count again, next time the value will be incremented in "interval".
					bpause = false;
					playpauset.setString("");
					
				}
				else
				{
					sound.pause();
					bpause = true;
					interval += playtime1.getElapsedTime();
					playpauset.setString("Paused");
				}

			}

			//the part for playing the last recording that has been made.
			if(event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::P)
			{

				if(last1) // the bool variable for checking whether the last recording wa made at 44100hz.
				{
					string count = itoa(recCount44);
					if (!record.loadFromFile("recording 44100 - " + count + ".wav")) //load file.
						cout <<"File could not be loaded." << endl;
					else
					{
						sound.setBuffer(record);
						sound.play();
						playtime.restart();
						playtime1.restart();
						duration = record.getDuration();
						bplay = true;
						bpause = false;
						playpauset.setString("");
					

						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i<count; i++)
						{
							//cout << *samples;
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);  // some changes to make it look good on the screen.
									//cout << max << endl;
								}

								max = *samples;
							}
							else if(abs(*samples) >= max) //if the sample value is larger then the max value it should be the new maximum.
								max = *samples;
							samples++; // the next memory location.
						}
					}


				}

				else if(last2) //the bool variable for checking whether the last recording wa made at 22050hz.
				{
					string count = itoa(recCount22);
					if (!record.loadFromFile("recording 22050 - " + count + ".wav"))
						cout <<"File could not be loaded." << endl;
					else
					{
						sound.setBuffer(record);
						sound.play();
						playtime.restart();
						playtime1.restart();
						sf::Time sec0 = sf::seconds(0);
						interval = sec0;
						duration = record.getDuration();
						bplay = true;
						bpause = false;
						playpauset.setString("");

						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i<count; i++)
						{
							//cout << *samples;
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);  // some changes to make it look good on the screen.
									//cout << max << endl;
								}

								max = *samples;
							}
							else if(abs(*samples) >= max) //if the sample value is larger then the max value it should be the new maximum.
								max = *samples;
							samples++; // the next memory location.
						}
					}
				}

				else if(last3) //last recording = 11025.
				{
					string count = itoa(recCount11);
					if (!record.loadFromFile("recording 11025 - " + count + ".wav"))
						cout <<"File could not be loaded." << endl;
					else
					{
						sound.setBuffer(record);
						sound.play();
						playtime.restart();
						playtime1.restart();
						duration = record.getDuration();
						bplay = true;
						bpause = false;
						playpauset.setString("");

						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i<count; i++)
						{
							//cout << *samples;
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);  // some changes to make it look good on the screen.
									//cout << max << endl;
								}

								max = *samples;
							}
							else if(abs(*samples) >= max) //if the sample value is larger then the max value it should be the new maximum.
								max = *samples;
							samples++; // the next memory location.
						}
					}
				}

				else if(last4) //last recording = 5012.
				{
					string count = itoa(recCount50);
					if (!record.loadFromFile("recording 5012 - " + count + ".wav"))
						cout <<"File could not be loaded." << endl;
					else
					{
						sound.setBuffer(record);
						sound.play();
						playtime.restart();
						playtime1.restart();
						duration = record.getDuration(),
						bplay = true;
						bpause = false;
						playpauset.setString("");

						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i<count; i++)
						{
							//cout << *samples;
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);  // some changes to make it look good on the screen.
									//cout << max << endl;
								}

								max = *samples;
							}
							else if(abs(*samples) >= max) //if the sample value is larger then the max value it should be the new maximum.
								max = *samples;
							samples++; // the next memory location.
						}

					}
				}

				else
				{
					cout << "No file has been recorded yet." << endl; // to avoid problems.
				}		
			}

			//the part for opening an audio file from the file directories.
			if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::O)
			{
				nfdchar_t *outPath = NULL;
				nfdresult_t result = NFD_OpenDialog("wav, ogg", NULL, &outPath ); // open dialog returs NFD_OKAY if the user did some action succesfully. 
				//waw, ogg is the filter I applied on he file dialog and the outhpath variable is the file's directory which is passed as a reference.

				if ( result == NFD_OKAY ) //if the user tried to open a file.
				{
					string out = outPath;
					if(!record.loadFromFile(out))
						cout << "File could not be loaded." << endl;
					else
					{
						sound.setBuffer(record);
						sound.play();
						playtime.restart();
						playtime1.restart();
						duration = record.getDuration(),
							bplay = true;

						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.
						waver.loadFromSamples(&samples[0], count, 1, record.getSampleRate()); //transform it into mono.
						//cout << count << endl;

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i<count; i++)
						{
							//cout << *samples;
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);  // some changes to make it look good on the screen.
									//cout << max << endl;
								}

								max = *samples;
							}
							else if(abs(*samples) >= max) //if the sample value is larger then the max value it should be the new maximum.
								max = *samples;
							samples++; // the next memory location.
						}
					}

				}
				else if ( result == NFD_CANCEL ) //if the user gave up on doing something.
				{
					puts("User pressed cancel.");
				}
				else 
				{
					cout << NFD_GetError();
				}
			}


			//for reducing 16 bit file to 8 bit file.
			if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Num8)
			{
				//again the file directories.
				nfdchar_t *outPath = NULL;
				nfdresult_t result = NFD_OpenDialog("wav, ogg", NULL, &outPath );

				if ( result == NFD_OKAY ) 
				{
					string out = outPath;
					
					if(!record.loadFromFile(out))
						cout << "File could not be loaded." << endl;
					else
					{
						const sf::Int16* samples = record.getSamples(); //gets the address of the first sample
						std::size_t count = record.getSampleCount(); //gets the sample count.
						sf::Int16 * ussamples = new sf::Int16 [count]; //the 8 bit version of the samples. I used sf::Int16 since sfml audio format is strictly that one.

						for(int i = 0; i<count; i++)
						{
							ussamples[i] = samples[i] & 0xFF00; //since the 8 bit audio is losing 16 bit audio's least significant bit parts i used a mask.
							//IMPORTANT: the reason i didn't use shift right operation was due to the fact that in most of samples the audio doesn't exceed a value around 4000.
							//therefore using right shifting made my samples so small that they were insignificant.
							//I first used an approach of converting signed16 to unsigned16 to unsigned8. But the results were not good. So I used this method.
						}

						//getting the values to draw the waveform.
						int max = -1000000000; //it should be fairly small so it shouldn't effect the results.
						ycor.clear();

						for(int i= 0; i< count; i++)
						{
							int ratio = count / 650; //how many samples per pixel on the screen.

							if(i % ratio == 0) //at each iteration of the radio we want to display the maximum value as the wave form.
							{
								if(i != 0) //since when i=0, max = -1000000.
								{
									ycor.push_back(-(max/200)+200);
									//cout << max << endl;
								}

								max = ussamples[i];
							}
							else if(abs(ussamples[i]) >= max)
								max = ussamples[i];
						}

						waver.loadFromSamples(&ussamples[0], count, 1, record.getSampleRate()); //to mono.
						sound.setBuffer(waver);
						sound.play();
						playtime.restart();
						playtime1.restart();
						duration = record.getDuration(),
							bplay = true;

						size_t poss = out.rfind('\\');
						size_t pose =out.rfind('.');
						if (poss != string::npos)
						{
							waver.saveToFile(out.substr(poss + 1,pose - (poss + 1)) + " 8 bit version.wav" );
						}
						else
							waver.saveToFile("8 bit audio.wav");

					}
				}
			}
		}

		window.clear();
		//drawing the waveform.
		// i wanted my waveform to look like dots connected to each other, exactly like a wave instead of points or columns.
		int j= 20; // the starting x coordinate.
		for(int i= 0; i<ycor.size(); i++)
		{
			if(ycor[i] != ycor [i+1])
				rectangle.setSize(sf::Vector2f(2,fabs(ycor[i] * 1.0- ycor[i+1]))); //the rectange's length is the difference between the two values so they look as if they are connected.
			else 
				rectangle.setSize(sf::Vector2f(2,1)); //if two values are the same there should be a straight line.

			if(ycor[i] < ycor[i+1]) //since on a computer the y coordinate gets bigger when moving to the bottom of the screen, the rectangle should be positioned on the left value iff it is smaller than the right value.
				rectangle.setPosition(j, ycor[i]);
			else
				rectangle.setPosition(j, ycor[i+1]);
			rectangle.setFillColor(sf::Color::White);
			window.draw(rectangle);
			j = j+2; //since with one square we draw on 2 pixels.
		}
		window.draw(record1);
		window.draw(record2);
		window.draw(record3);
		window.draw(record4);
		window.draw(rec);
		window.draw(opent);
		window.draw(playt);
		window.draw(pause);
		window.draw(playpauset);
		window.draw(bit8t);
		window.display();
	}
	return 0;
}
コード例 #13
0
ファイル: Huffman.cpp プロジェクト: MossFrog/CPP-Bundle
int main()
{
    //mainTree.resize(1000000);
    cout << "Please select and Input file." << endl;

    nfdchar_t *outPath = NULL;
    nfdresult_t result = NFD_OpenDialog("txt", NULL, &outPath);

    if (outPath != NULL && outPath != "")
    {
        //-- Push the contents of the text file to a string variable --//
        textStream.open(outPath);
        while (getline(textStream, inLines))
        {
            inputText += inLines + '\n';
        }

        textStream.close();

        //-- Loop throughout the entire text and get every character's count --//

        for (int i = 0; i < inputText.length(); i++)
        {
            bool present = false;

            //-- Parse through the Character Count Vector and search for a Match --//
            for (int j = 0; j < charCountVect.size(); j++)
            {
                if (charCountVect[j].val[0] == inputText[i])
                {
                    //-- If the character is present increment the character count --//
                    present = true;
                    charCountVect[j].count++;
                }
            }

            //-- If a new character is encountered then add it to the Character Count Vector --//
            if (!present)
            {
                character newChar;
                newChar.val = inputText[i];
                newChar.count = 1;

                charCountVect.push_back(newChar);
            }
        }

        //-- Inefficiently sort the contents of the Character Count Vector --//

        for (int i = 0; i < charCountVect.size(); i++)
        {
            for (int j = 0; j < charCountVect.size(); j++)
            {
                if (charCountVect[i].count < charCountVect[j].count)
                {
                    swap(charCountVect[i], charCountVect[j]);
                }
            }
        }


        expectedCount = charCountVect.size();


        //-- Debugging section --//
        /*
        for (int i = 0; i < charCountVect.size(); i++)
        {
        cout << charCountVect[i].val << ": " << charCountVect[i].count << endl;
        }
        */

        //-- Create the base of the tree --//

        for (int i = 0; i < charCountVect.size(); i++)
        {
            node newNode;
            newNode.charVal += charCountVect[i].val;
            newNode.numVal = charCountVect[i].count;
            newNode.left = "";
            newNode.right = "";
            newNode.father = "";
            newNode.topLayer = true;
            mainTree.push_back(newNode);
            pinnacleNode = newNode;
        }


        //-- Continue constructing the tree upon the base removing combined Nodes. --//
        while (charCountVect.size() > 1)
        {
            //-- Select Two Arbitrary Minima --//
            node minOne;
            node minTwo;
            int indexOne;
            int indexTwo;

            minOne.numVal = INT_MAX;
            minTwo.numVal = INT_MAX;

            //-- Remove minima one from the value array after discovery --//
            for (int i = 0; i < charCountVect.size(); i++)
            {
                if (charCountVect[i].count < minOne.numVal)
                {
                    minOne.charVal = charCountVect[i].val;
                    minOne.numVal = charCountVect[i].count;
                    indexOne = i;
                }
            }

            charCountVect.erase(charCountVect.begin() + indexOne);

            //-- Do the same for minima two --//
            for (int i = 0; i < charCountVect.size(); i++)
            {
                if (charCountVect[i].count < minTwo.numVal)
                {
                    minTwo.charVal = charCountVect[i].val;
                    minTwo.numVal = charCountVect[i].count;
                    indexTwo = i;
                }
            }

            charCountVect.erase(charCountVect.begin() + indexTwo);

            int tindexOne;
            int tindexTwo;

            //-- Retrieve minOne and minTwo's indeces in the main tree Vector --//
            for (int i = 0; i < mainTree.size(); i++)
            {
                if (mainTree[i].charVal == minOne.charVal)
                {
                    tindexOne = i;
                }

                else if (mainTree[i].charVal == minTwo.charVal)
                {
                    tindexTwo = i;
                }
            }

            //-- Debugging Section --//
            /*
            cout << minOne.charVal << " " << minOne.numVal << endl;
            cout << minTwo.charVal << " " << minTwo.numVal << endl;
            cin.ignore();
            */

            //-- Merge the two minima togeather and update both the tree and the Vector. --//

            node combinedNode;
            combinedNode.charVal = minTwo.charVal + minOne.charVal;
            combinedNode.numVal = minOne.numVal + minTwo.numVal;
            combinedNode.father = "";
            combinedNode.left = mainTree[tindexTwo].charVal;
            combinedNode.right = mainTree[tindexOne].charVal;
            combinedNode.topLayer = true;
            pinnacleNode = combinedNode;

            //-- Push the combined node to the tree and the character count Vector --//
            mainTree.push_back(combinedNode);

            character tempChar;
            tempChar.val = combinedNode.charVal;
            tempChar.count = combinedNode.numVal;
            charCountVect.push_back(tempChar);


            //-- Update the father values --//

            mainTree[tindexOne].father = combinedNode.charVal;
            mainTree[tindexTwo].father = combinedNode.charVal;

        }


        //-- Debugging Section --//
        /*
        cout << mainTree[0].charVal << endl;
        cout << mainTree[0].father << endl;
        cin.ignore();*/

        //-- Update all the values in the decode vector according to the mainTree --//

        for (int i = 0; i < mainTree.size(); i++)
        {
            //-- If the value is an end branch --//
            if (mainTree[i].charVal.length() == 1)
            {
                node tempNode;
                tempNode = mainTree[i];
                int fatherIndex;
                while (tempNode.father != "")
                {
                    //-- Locate the father --//
                    for (int j = 0; j < mainTree.size(); j++)
                    {
                        if (tempNode.father == mainTree[j].charVal)
                        {
                            fatherIndex = j;

                            if (tempNode.charVal == mainTree[j].left)
                            {
                                mainTree[i].bitVal = "0" + mainTree[i].bitVal;
                            }

                            else
                            {
                                mainTree[i].bitVal = "1" + mainTree[i].bitVal;
                            }
                        }
                    }

                    //-- Update tempnode --//
                    tempNode = mainTree[fatherIndex];
                }
            }
        }

        string keyStr = "";

        for (int i = 0; i < mainTree.size(); i++)
        {
            //-- If the value is an end branch --//
            if (mainTree[i].charVal.length() == 1)
            {
                //-- Uncomment this section to see each character's encoding --//
                //cout << mainTree[i].charVal << " " << mainTree[i].bitVal << endl;

                keyStr = keyStr + mainTree[i].charVal + ": " + mainTree[i].bitVal + '\n';
            }
        }


        //-- Encode the whole text and also save the key to another folder --//

        string encodedOutput = "";

        for (int i = 0; i < inputText.length(); i++)
        {
            int decodeIndex = 0;
            //-- Find the encoded character representation --//
            while ((inputText[i] != mainTree[decodeIndex].charVal[0]) || (mainTree[decodeIndex].bitVal.length() == 0))
            {
                decodeIndex++;
            }

            //-- Uncomment this section to see step by step encoding process --//
            /*
            cin.ignore();
            cout << inputText[i] << ": " << mainTree[decodeIndex].bitVal << endl;
            */

            encodedOutput += mainTree[decodeIndex].bitVal;
        }


        //-- Output both texts --//
        cout << endl << "-- Original Text --" << endl << endl;
        cout << inputText << endl;
        cout << endl;

        cin.ignore();

        cout << endl << "-- Encoded Text --" << endl << endl;
        cout << encodedOutput << endl;
        cout << endl;

        //-- Dump the key and the text to an output file --//
        outputStream.open("EncodedOutput.txt");
        outputStream << encodedOutput;
        outputStream.close();

        outputStream.open("Key.txt");
        outputStream << keyStr;
        outputStream.close();


    }

    else
    {
        cout << "You did not select a valid file" << endl;
        cout << endl;
    }

    cout << "--- Ending Program ---" << endl;
    cin.ignore();
    return 0;
}