ườ
Tr
ọ ự ng ĐH Khoa H c T Nhiên TP.HCM
TRUNG TÂM TIN H CỌ
ậ
ạ
ầ
GV Biên so n: Tr n Duy Thanh
L p trình Windows Phone Module 3 – Bài 2: Multimedia
2014
Nội dung
• Giới thiệu Multimedia
• Cách sử dụng Camera & Photo
• Làm việc với Video
• Làm việc với Audio
2
ậ
L p trình Windows Phone – Multimedia
1. Giới thiệu Multimedia
ü Windows Phone hỗ trợ đa phương tiện rất mạnh mẽ, lập trình viên có thể tương tác được với Camera, Pho, Video và Audio.
ü Trong giới hạn của phần này người học sẽ được cung cấp các kiến thức nền tảng và nâng cao về cách tương tác tới Camera: Cách Preview, cách chụp, cách lưu trữ hình ảnh; Video: Cách play, pause, stop, mute, seek, ghi âm; Audio: Cách đưa Sound File vào ứng dụng cũng như cách thức lập trình cho Audio chạy background.
ü Học viên sẽ được củng cố them kiến thức về
3
ậ
L p trình Windows Phone – Multimedia
MediaElement, MediaPlayerLauncher…
2. Cách sử dụng Camera & Photo Ø Chế độ Camera Preview
Ø Chụp hình từ Camera
Ø Sử dụng Camera với ViewModel
Ø Thiết lập hiệu ứng âm thanh cho Camera
Ø Tạo Camera Focus
4
ậ
L p trình Windows Phone – Multimedia
2.1 Chế độ Camera Preview
Ø Sử dụng 2 lớp thư viện dưới đây:
ü PhotoCamera
ü VideoBrush
Chế độ Camera Preview cho phép chúng ta xem trước khung cảnh, để có thể chụp được một bức ảnh thì ta phải khởi tạo PhotoCamera và cung trong ID_CAP_ISV_CAMERA cấp WMAppManifest.xml Capabilities.
Hai lớp trên nằm trong:
5
ậ
L p trình Windows Phone – Multimedia
using Microsoft.Devices; using System.Windows.Media;
2.1 Chế độ Camera Preview
6
ậ
L p trình Windows Phone – Multimedia
private PhotoCamera _camera; private VideoBrush _videoBrush; protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); _camera = new PhotoCamera(CameraType.Primary); _camera.Initialized += _camera_Initialized; _videoBrush = new VideoBrush(); _videoBrush.SetSource(_camera); }
2.1 Chế độ Camera Preview
7
ậ
L p trình Windows Phone – Multimedia
ạ ể
void _camera_Initialized(object sender, CameraOperationCompletedEventArgs e) { if (e.Succeeded) //ki m tra kích ho t thành công { var resolution = new Size(2048, 1536); if (_camera.AvailableResolutions.Contains(resolution)) { _camera.Resolution = resolution; } Dispatcher.BeginInvoke(() => { this.LayoutRoot.Background = _videoBrush; }); } }
2.2. Chụp hình từ Camera
Ø Sự kiện Người sử dụng bấm nút chụp:
Để có thể chụp hình được từ Camera ta cần ID_CAP_MEDIALIB_PHOTO capability và thêm 2 sự kiện sau vào quá trình khởi tạo:
CameraButtons.ShutterKeyPressed +=
Ø Khi hình ảnh sẵn sàng được chụp:
CameraButtons_ShutterKeyPressed;
_camera.CaptureImageAvailable +=
8
ậ
L p trình Windows Phone – Multimedia
_camera_CaptureImageAvailable;
2.2. Chụp hình từ Camera
9
ậ
L p trình Windows Phone – Multimedia
void CameraButtons_ShutterKeyPressed (object sender, EventArgs e) { try { _camera.CaptureImage(); } catch (InvalidOperationException ex) { this.Dispatcher.BeginInvoke(() => { MessageBox.Show(ex.Message); }); } }
2.2. Chụp hình từ Camera
void _camera_CaptureImageAvailable (object sender, ContentReadyEventArgs e) { string path = "picture_drthanh.jpg"; MediaLibrary library = new MediaLibrary(); library.SavePictureToCameraRoll
(path, e.ImageStream);
10
ậ
L p trình Windows Phone – Multimedia
}
2.3. Sử dụng Camera với ViewModel Để giảm thiểu thời gian coding, người ta sử dụng Camera ViewModel và binding tới trang ứng dụng.
• Tạo
Các bước chính cần làm:
lớp BaseViewModel kế thừa từ
• Tạo
INotifyPropertyChanged.
lớp CameraViewModel kế thừa từ
• Binding tới VideoBrush:
BaseViewModel và IDisposable
11 L p trình Windows Phone – Multimedia ậ
ü Chi tiết xem giáo trình trang 6 Background="{Binding Preview}"/> Ø Việc đưa âm thanh vào quá trình chụp hình
trong Camera là khá quan trọng và hấp dẫn,
mỗi khi người sử dụng bấm nút chụp thì
chương trình sẽ phát ra những âm thanh để
có thể biết được thao tác thành công hay thất
bại. Ø Ta sử dụng các thư viện sau: using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using System.Windows.Resources; using System.Windows; 12 ậ L p trình Windows Phone – Multimedia ướ ấ ng SoundEffect: Ø B c 1: L y Stream Resource sound file:
Uri uri=new Uri("Stop.wav", UriKind.Relative);
StreamResourceInfo resource =
Application.GetResourceStream(uri);
ố ượ
Ø B c 2: l y đ i t
var effect = SoundEffect.FromStream(resource.Stream);
Ø B c 3: G i hàm Update đ g i thông đi p t ệ ớ ể ử ướ ọ i XNA Framework: ươ ọ ể ở ứ ng th c Play đ m sound: 13 ậ L p trình Windows Phone – Multimedia FrameworkDispatcher.Update();
ướ
Ø B c 4: G i ph
effect.Play();
ü Chi tiết xem trang 11 ØThường thì Camera hỗ trợ chúng ta chức
năng Focus vào một đối tượng hay một vùng
nào đó trong quá trình chúng sử dụng. ØDùng thức phương Focus() 14 ậ L p trình Windows Phone – Multimedia và
FocusAtPoint() để thiết lập focus. Khi quá trình
Focus hoàn thành thì nó sẽ tự động xuất hiện sự
kiện AutoFocusCompleted, dùng sự kiện này
để ta xử lý nhiều kết quả. ØChú ý là ta phải dùng Canvas để có thể di
chuyển được ô Focus tới vị trí bất kỳ trên màn
hình điện thoại. 15 ậ L p trình Windows Phone – Multimedia public void Focus() {
if ((_camera.IsFocusSupported) && (!_isCapturing))
{
Deployment.Current.Dispatcher.BeginInvoke(()
=> {
this.IsFocusing = true;
});
_camera.Focus();
}
} 16 ậ L p trình Windows Phone – Multimedia public void FocusAtPoint(double x, double y)
{
if ((_camera.IsFocusAtPointSupported) &&
(!_isCapturing)) {
Deployment.Current.Dispatcher.BeginInvoke(()
=> {
this.IsFocusing = true;
});
_camera.FocusAtPoint(x, y);
}
}
Chi tiết xem trang 16 Ø MediaElement và MediaPlayerLauncher Ø Các thao tác thường sử dụng: ü Play ü Stop ü Pause ü Mute ü Seek ü Record 17 ậ L p trình Windows Phone – Multimedia Ø MediaElement 18 ậ L p trình Windows Phone – Multimedia Source="film.wmv"/> Ø MediaPlayerLauncher MediaPlayerLauncher player =
new MediaPlayerLauncher(); 19 ậ L p trình Windows Phone – Multimedia player.Media = new Uri("film.wmv", UriKind.Relative);
player.Location = MediaLocationType.Install;
player.Show(); ü Stop ü Pause ü Mute ü Seek ü Record 20 ậ L p trình Windows Phone – Multimedia private void btnPlay_Click (object sender, RoutedEventArgs e) 21 ậ L p trình Windows Phone – Multimedia {
if (this.CanPlay())
{
mediaPlayer.Play();
}
} private void btnStop_Click (object sender, RoutedEventArgs e) {
mediaPlayer.Stop();
mediaPlayer.Position = System.TimeSpan.FromSeconds(0); 22 ậ L p trình Windows Phone – Multimedia lblStatus.Text = "Stopped";
} private void btnPause_Click (object sender, RoutedEventArgs e) { 23 ậ L p trình Windows Phone – Multimedia if (mediaPlayer.CanPause)
{
mediaPlayer.Pause();
lblStatus.Text = "Paused";
}
else {
lblStatus.Text = "Can not be Paused!!";
}
} 24 ậ L p trình Windows Phone – Multimedia private void btnMute_Click (object sender, RoutedEventArgs e){
if (lblSoundStatus.Text.Equals("Sound On",
StringComparison.CurrentCultureIgnoreCase)) {
lblSoundStatus.Text = "Sound Off";
mediaPlayer.IsMuted = true;
} else {
lblSoundStatus.Text = "Sound On";
mediaPlayer.IsMuted = false;}
} Thường ta dùng Slider để di chuyển 25 ậ L p trình Windows Phone – Multimedia private void mediaTimeline_ValueChanged(object sender,
RoutedPropertyChangedEventArgs mediaPlayer.NaturalDuration.TimeSpan;
int newPosition = (int)(duration.TotalSeconds * mediaTimeline.Value); 26 ậ L p trình Windows Phone – Multimedia mediaPlayer.Position =
new TimeSpan(0, 0, newPosition); }
} Để quay Video ta cần dùng các thư viện sau: using System.Windows.Media;
using System.IO;
using System.IO.IsolatedStorage;
using Microsoft.Xna.Framework.Media;
Ta có 3 thao tác chính:
Preview – xem tr
Record – Quay
Playback – Phát l 27 ậ L p trình Windows Phone – Multimedia private void Preview() { VideoPlayer.Stop(); VideoPlayer.Source = null; _captureSource.Stop(); _videoBrush.SetSource(_captureSource); recordvideo.Background = _videoBrush; _captureSource.Start(); 28 ậ L p trình Windows Phone – Multimedia } 29 ậ L p trình Windows Phone – Multimedia private void Record()
{
_captureSource.Stop();
using (IsolatedStorageFile store =
IsolatedStorageFile.GetUserStoreForApplication())
{
store.CreateFile(path).Close();
}
_fileSink.CaptureSource = _captureSource;
_captureSource.Start();
} 30 ậ L p trình Windows Phone – Multimedia private void Playback() {
_captureSource.Stop();
IsolatedStorageFile store
=IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists(path)) {
IsolatedStorageFileStream isoStream = new
IsolatedStorageFileStream (path,FileMode.Open, FileAccess.Read, store);
VideoPlayer.SetSource(isoStream);
VideoPlayer.MediaEnded += new
RoutedEventHandler(VideoPlayer_MediaEnded);
VideoPlayer.Play();
}
} Ø Thêm âm thanh vào ứng dụng Ø Cách chạy Audio Background 31 ậ L p trình Windows Phone – Multimedia Ta cũng sử dụng các thư viện sau: 32 ậ L p trình Windows Phone – Multimedia using Microsoft.Xna.Framework.Media;
using Microsoft.Xna.Framework; (object sender, RoutedEventArgs e) 33 ậ L p trình Windows Phone – Multimedia {
if (CanPlay()) {
mymedia.Stop();
mymedia.Source = new
System.Uri("sound.wma", System.UriKind.Relative);
mymedia.Play();
}
} ü AudioPlayerAgent, ü AudioStreamingAgent 34 ậ L p trình Windows Phone – Multimedia 35 ậ L p trình Windows Phone – Multimedia • OnPlayStateChanged: Hàm này để tự động
kiểm tra sự thay đổi trạng thái play, bao gồm:
buffering, playing, track ready, track ended, và
shutdown. • OnUserAction: Hàm này sẽ được triệu gọi khi
người sử dụng tiến hành những thao tác nào
đó trong Application’s audio playlist ở vòng đời
Foreground (dùng controls provider hoặc
Universal Volume Control) • OnError: Hàm này sẽ được triệu gọi khi có lỗi 36 ậ L p trình Windows Phone – Multimedia sảy ra trong quá trình audio playback. 37 ậ L p trình Windows Phone – Multimedia • OnBeginStreaming: Hàm này sẽ được triệu • OnCancel: Hàm này sẽ được triệu gọi khi gọi khi ta bắt đầu Audio Streaming Audio Stream bị hủy. 38 ậ L p trình Windows Phone – Multimedia Chi tiết cách chạy nền xem trang 31 39 ậ L p trình Windows Phone – Multimedia2.4. Thiết lập hiệu ứng âm thanh cho Camera
2.4. Thiết lập hiệu ứng âm thanh cho Camera
ấ
ướ
2.5. Tạo Camera Focus
ØTa sử dụng thuộc tính IsFocusSupported,
IsFocusAtPointSupported của PhotoCamera
để kiểm tra xem camera có hỗ trợ Focus hay
không.
2.5. Tạo Camera Focus
2.5. Tạo Camera Focus
3. Làm việc với Video
3.1. MediaElement và MediaPlayerLauncher
3.1. MediaElement và MediaPlayerLauncher
3.2. Các thao tác thường sử
dụng
ü Play
3.2. Các thao tác thường sử
dụng
ü Play
3.2. Các thao tác thường sử
dụng
ü Stop
3.2. Các thao tác thường sử
dụng
ü Pause
3.2. Các thao tác thường sử
dụng
ü Mute
3.2. Các thao tác thường sử
dụng
ü Seek
3.2. Các thao tác thường sử
dụng
ü Seek
3.2. Các thao tác thường sử
dụng
ü Record
cướ
iạ
3.2. Các thao tác thường sử
dụng
ü Preview
3.2. Các thao tác thường sử
dụng
ü Record
3.2. Các thao tác thường sử
dụng
ü Playback
4. Làm việc với Audio
4.1. Thêm âm thanh vào ứng
dụng
Ø Giống như việc đưa Video vào ứng dụng
4.1. Thêm âm thanh vào ứng
dụng
private void btnPlay_Click
4.2. Cách chạy Audio
Background
Ø Có 2 cách chạy nền:
4.2. Cách chạy Audio
Background
ü AudioPlayerAgent
4.2. Cách chạy Audio
Background
ü AudioPlayerAgent
4.2. Cách chạy Audio
Background
ü AudioStreamingAgent
4.2. Cách chạy Audio
Background
ü AudioStreamingAgent
Thảo luận